INSTRUCTION
stringlengths
11
999
RESPONSE
stringlengths
0
999
SOURCE
stringlengths
16
38
METADATA
dict
how can i get records from wp_postmeta table using particular meta_key in database? In plugin development, how to fetch data from database of particular data in dropdown list? global $wpdb; $id = 'parent_id'; $data = $wpdb->get_results("SELECT * FROM wp_postmeta WHERE meta_key = $id"); echo $data; i get results as array how can i get all values in dropdown list? Can you please help?
<select name="parent_id" id="parent-id"> <?php $sql = "SELECT meta_value FROM wp_postmeta WHERE meta_key='parent_id'"; $results = $wpdb->get_results($sql) or die(mysql_error()); foreach( $results as $result ) { ?> <?php echo $result->meta_value;?> <option <?php if ($result->meta_value == $parent) echo 'selected="selected" ';?> > <?php //echo $result->meta_value; ?> <?php echo $result->meta_value; ?> </option> <?php } ?> </select>
stackexchange-wordpress
{ "answer_score": 0, "question_score": 0, "tags": "plugins, plugin development, database" }
Monarch JS has not been loaded. After changing the $dep parameter, it start being loaded When use this code does not work wp_enqueue_script( 'et_monarch-custom-js', ET_MONARCH_PLUGIN_URI . '/js/custom.js', array( 'jquery' ), $this->plugin_version, true ); But this one works wp_enqueue_script( 'et_monarch-custom-js', ET_MONARCH_PLUGIN_URI . '/js/custom.js', array(), $this->plugin_version, true );
Your code looks fine and should work. So that leads to the conclusion that jquery is not loaded at the time you are trying to load your script. Since WP is loading jquery by default, this leaves two possibilities: 1. You are loading your script before jquery is loaded with a high priority on you `add_action` 2. You (or a plugin you are using) are deregistering jquery, possibly to register it again at a later point. Your script is trying to load right inbetween.
stackexchange-wordpress
{ "answer_score": 2, "question_score": -1, "tags": "jquery, wp enqueue script" }
How to prevent queried posts from being added to cache? I'm learning about caching parameters and tried this in the `single.php` template: echo count($wp_object_cache->cache['posts']); $query = new \WP_Query([ 'post_type' => 'post', 'cache_results' => false, 'posts_per_page' => 5, 'ignore_sticky_posts' => true ]); echo '<br>' . count($wp_object_cache->cache['posts']); The result: 3 7 Somehow, the `cache_results` parameter didn't work. Am I missing something? * * * I'm using: * WordPress version 4.6. * Twentyfifteen theme. * No plugins/third party services.
The posts array result in `WP_Query` is mapped to `get_post()` (here and here) with: $this->posts = array_map( 'get_post', $this->posts ); and that seems to be adding posts to the _object cache_ even though the `cache_results` argument is set to `false` in `WP_Query`. Within the `get_post()` function (here) we have: $_post = WP_Post::get_instance( $post ); for the case when `$post` is neither a `WP_Post` or an object instance. The `WP_Post::get_instance` method contains `wp_cache_get()` and `wp_cache_set()` calls. So that could explain the behavior you see in your example.
stackexchange-wordpress
{ "answer_score": 2, "question_score": 2, "tags": "wp query, cache" }
Featured image doesn't appear in Blog index I am using a static page for my frontpage, and another page for my blog index. However, I've noticed that if I use the same code from my page.php file for displaying the featured image (which works fine), it will not show the featured image for the page designed as my blog index page. Why is this? This is the snippet of code from page.php, from the top of the file: <?php get_header(); ?> <?php if ( has_post_thumbnail() ) { echo 'Featured image here'; } ?> But this code will not produce the echoed result when placed in index.php
Managed to find an alternative function that correctly calls the featured image set for the Blog index page by using this: <?php get_header(); ?> <?php if ( is_home() && get_option('page_for_posts') ) { echo get_the_post_thumbnail_url( get_option('page_for_posts') ); } ?> Thanks to those for your help
stackexchange-wordpress
{ "answer_score": 0, "question_score": 0, "tags": "post thumbnails, blog" }
How to show updated edit on preview URL without clicking preview button ^ This is the preview URL for a page with id 19, now whenever I made some changes to it's page content and refresh above URL it don't show the latest changes I made unless I click preview button, I think preview button trigger some kind of function which save page and then above URL shows the latest edit, I want to know can I call that function which preview button calls when clicked.
Yes, though it's not very well documented and it's not clear if it forms part of the public API. When you click preview, WordPress saves a draft and opens the preview URL which shows the latest saved draft. You can see this by making a change, and waiting for WordPress' auto-save to kick in. If you do that, and refresh the preview URL it will show the latest draft without you having to click preview or save draft. So while you can never see a 'live preview' in a separate window. You could, if you wanted, prompt WordPress to save a draft when (for example), the text editor loses focus or the window loses focus. You will probably want to limit the number of revisions you keep, however. The autosave functionality can be found here: < The function you want to call is: if ( wp.autosave.server ) { wp.autosave.server.triggerSave(); }
stackexchange-wordpress
{ "answer_score": 4, "question_score": 2, "tags": "pages, core, previews" }
Make menu page link inaccessible or disabled I want to disable/hide the menu pages for users other than admin. I am able to successfully do it with the following logic. But the menu pages appear through the url. <?php function custom_menu_page_removing() { remove_menu_page( $menu_slug ); } add_action( 'admin_menu', 'custom_menu_page_removing' ); ?> Is there a way to disable the menu pages through the url also? Thanks in advance :)
To do that use the following function: add_action( 'admin_menu', 'custom_menu_page_removing' ); function custom_menu_page_removing() { global $pagenow; if ( !current_user_can( 'administrator' ) ) { $menu = array( 'edit.php', 'edit-comments.php' ); foreach ( $menu as $main ) { remove_menu_page( $main ); } if ( in_array( $pagenow, $menu, true ) && ( !isset( $_GET['post_type'] ) || isset( $_GET['post_type'] ) && $_GET['post_type'] == 'post' ) ) { wp_die( 'Access denied...' ); exit; } } } This will execute the function only if the user is **not** an admin. Where you see `edit.php` and `edit-comments.php`, you can replace and add more menu slug that you want to hide. Make sure you add a `,` after each one except for the last one.
stackexchange-wordpress
{ "answer_score": 1, "question_score": 1, "tags": "plugins, admin menu" }
Bulk remove post meta The site I am working on used to keep some data in posts meta. It is a WooCommerce site and the data was kept in products variations and fields names look like _field_name[12345] where 12345 is a variation id. That caused bloating of import/export files and creating a lot of rows in the database and the meta fields which keep this data now look like __field_name. Now I am looking for a simple (which will not take long to implement) solution to remove the fields like _field_name[12345] from all the variations. However, there are quite a lot of products on the site and just looping through all the products, each variation of each product and make delete_post_meta($variation_id) is not an option because we will run out of memory or time limit. Making an AJAX-based function which will break queries with a timeout does not fit the simple solution criteria. Can you please give me another idea of cleaning this mess?
Sometimes one just needs to ask to understand what the issue is. DELETE FROM `db_name`.`wp_postmeta` WHERE `wp_postmeta`. `meta_key` LIKE '_field_name[%]' did the trick.
stackexchange-wordpress
{ "answer_score": 1, "question_score": 1, "tags": "custom field, post meta, woocommerce offtopic" }
Callback for wp.autosave.server.triggerSave(); I'm using following code to force WordPress page to save post as draft, is there any callback function for it, I want to alert a text after it complete saving post as draft. if ( wp.autosave.server ) { wp.autosave.server.triggerSave(); }
So I found the solution, callback function for when post or page is: jQuery(document).on('heartbeat-tick.autosave', function( event, data ) { // your code here }); This uses the Wordpress Heartbeat API.
stackexchange-wordpress
{ "answer_score": 8, "question_score": 5, "tags": "posts, pages, callbacks, autosave" }
Remove rel='dns-prefetch' href='//maps.google.com' from wp-head How to remove this from WP head: <link rel='dns-prefetch' href='//maps.google.com'> I had this also: <link rel='dns-prefetch' href='//s.w.org'> But, I removed it with this code inside my functions.php add_filter( 'emoji_svg_url', '__return_false' ); Probably, this is added by one plugin exifografy, which can show map of location where image is taken. But, there is just few posts with map, so having this on all URL-s is just one more line of not used HTML code.
Resource Hints is a smart feature added to WordPress version 4.6. I think it might improve your site speed. But if you want to disable it, try this: remove_action('wp_head', 'wp_resource_hints', 2); * * * **References** * wp_head resource hints * wp_resource_hints filter
stackexchange-wordpress
{ "answer_score": 6, "question_score": 3, "tags": "wp head" }
Website redirecting to old domain name I was developing website on `test.example.com` on a separate server. Meanwhile, the working server was `example.com` at GoDaddy. The WordPress website was working fine on both servers. But then I changed the registrar and decided to change the WordPress on `test.example.com` to `example.com` inside of the `wp-config.php`. If I'm entering `example.com/wp-admin` \- it opens without problem. However, when I try `example.com` it redirects to `test.example.com`. Can't figure out why it's happening.
There are a few variables that need to be changed in order for you to update to the new link on your WordPress site. As mentioned by Mark, try the following steps using the Search Replace DB tool: 1. Go and download Interconnect IT's Database Search & Replace Script here 2. Unzip the file and drop the folder in your **localhost** where your WordPress is installed (the root) and rename the folder to **`replace`** (screenshot) 3. Navigate to the new folder you created in your browser (ex: ` and you will see the search/replace tool 4. It should be pretty self-explanatory up to this point: enter your old URL in the **`search for…`** field and the new URL in the **`replace with…`** field You can click the _dry run_ button under _actions_ to see what it will be replacing before you execute the script. Once you're done be sure to remove the `/replace/` folder.
stackexchange-wordpress
{ "answer_score": 3, "question_score": 2, "tags": "redirect, wp config, domain, dns" }
WordPress Redirect All HTTP requests to HTTPS via .htaccess I've done this many times before, and yet I'm not managing to do this again for some unknown reason. Tried endless solutions. Everything I've tried results in an endless redirect loop. What is the best option for doing this? **Update 1** Here are a few of the things tried; RewriteCond %{HTTP_HOST} ^website\.co\.uk [NC] RewriteCond %{SERVER_PORT} 80 RewriteRule ^(.*)$ [R,L] And; RewriteCond %{SERVER_PORT} 80 RewriteRule ^(.*)$ [R,L] Tested in different browsers to prevent caching issues. Still nothing, just getting continual redirect loop.
I see, when you enter a link to your page other than your home, example: * ` * `www.michaelcropper.co.uk/contact-me` * `michaelcropper.co.uk/contact-me` If ` is not in the prefix, the HTTP link loads instead. Add the following into your `.htaccess` in between the `<IfModule mod_rewrite.c>` tag: RewriteCond %{HTTPS} !=on RewriteRule ^(.*) [R,L] If there were no additional modifications done to your `.htaccess`, it should look like the following: # BEGIN WordPress <IfModule mod_rewrite.c> RewriteEngine On RewriteBase / RewriteRule ^index\.php$ - [L] RewriteCond %{REQUEST_FILENAME} !-f RewriteCond %{REQUEST_FILENAME} !-d RewriteRule . /index.php [L] # Rewrite HTTP to HTTPS RewriteCond %{HTTPS} !=on RewriteRule ^(.*) [R,L] </IfModule> # END WordPress Let me know how it goes.
stackexchange-wordpress
{ "answer_score": 21, "question_score": 12, "tags": "redirect, htaccess" }
My javascript jquery won't work? I am trying to make a mobile navigation for my site. However the jquery code won't work. You can see what I am trying to do here: jsfiddle. I have the html in my header.php after body tag, css in my style.css For javascript I enqueued it in my functions php: wp_enqueue_script( 'test', get_template_directory_uri() . '/js/testJS.js', array('jquery'), true ); In my testJS.js I have this code: ( function( $ ) { $(".mobileButton").click(function(){ $(this).toggleClass("toggle"); }); } )( jQuery ); But when I click on the button nothing happens unlike my jsfiddle. Can someone tell me what I did wrong? Thanks in advance!
Try loading your script in the footer: wp_enqueue_script( 'test', get_template_directory_uri() . '/js/testJS.js', array('jquery'), false, true );` The `true` parameter on the end tells WordPress to load this script in the footer instead of the header. For more information, visit the Codex: <
stackexchange-wordpress
{ "answer_score": 1, "question_score": 1, "tags": "theme development, jquery" }
WooCommerce: Conditional Tag for Wishlist Page I am using this plugin **YITH WooCommerce Wishlist** now I want to excute some code on wishlistpage how can i do this for other pages i have used conditional tags list **is_home() , is_product_category()** etc is there any conditional tag for wishlist page please help me out..
If you mean the Wishlist Page were all the wishlist items of a user are displayed, then actually its a single page so you could use is_page() function and pass the ID / slug of that page and then use it as a conditional tag to execute some code.
stackexchange-wordpress
{ "answer_score": 0, "question_score": 0, "tags": "woocommerce offtopic" }
Wordpress with Git I am asking this question because I searched on internet but cannot find right solution. Actually I want a solution in which multiple developers can work on single wordpress project without creating any mess into each other works, but as we know that in wordpress every thing is maintained in database like which plugin is active and which is not. If developers install plugins to their local project than how they communicate with each other that every one should install that particular plugin or plugins etc, and some miscommunication can break the site of others if every every developer push/pull the code. Should we share the database too, to share the plugin/themes settings so that there should no conflicts or little conflicts between the developers. Thanks
**Git for plugins** : * Use Composer for plugins which are already packaged on packagist or wpackagist. Add them to `composer.json`. * Use TGM Plugin Activation for other plugins. Then, use Git to manage `composer.json` and the changes in the TGM plugin. **The hardest part is to sync database** : Definitely, we should share database. Reconfigure a plugin settings/options is not a good idea. There're many plugins, both free and premium, which can help. If you want to try something manually, incorporate wp-cli with the answer of @Wyck.
stackexchange-wordpress
{ "answer_score": 19, "question_score": 23, "tags": "git" }
Wordpress Comments - Rich Text I've had a question from a client to enable image based stickers in the comment system. I've built a basic jQuery script which will allow the selection of a sticker and add it as markup in the comment textarea; jQuery(".stickers img").click(function(){ var img = jQuery(this).parent().html(); var text = jQuery("#respond textarea").val(); jQuery("#respond textarea").val(text + img); }); While this works just fine upon hitting submit, the user is presented with raw HTML code until this happens. I did see a plugin called "Rich Text Editor for Comments", but this appears to have been removed for the WP repository. Does anyone know of a similar plugin, or how the comment textarea could be adapted to use rich text by default?
I have found a way by using nicEdit here's the tutorial. In order to get this fully functioning, I had to amend my script slightly. jQuery(".stickers img").click(function(){ var img = jQuery(this).parent().html(); var text = jQuery("#respond .nicEdit-main").html(); jQuery("#respond .nicEdit-main").html(text + img); }); I hope this helps someone.
stackexchange-wordpress
{ "answer_score": 0, "question_score": 1, "tags": "jquery, comments, html" }
Add Capabilities to Custom Post Type after it has been created I have a custom post type that is created by an external plugin. This plugin uses the capabilities associated with posts. I want to add my own custom capabilities to this post type. I have seen plenty of examples of how to do this when registering a new post type but I can't add the capabilities at this point as otherwise the custom capabilities won't be there when I next update the plugin. What would be the best way to add the capabilities after the custom post type has been created? Thanks!
Irrespective of the plugin you use > each plugin will give you an option to save / view the PHP code generated for the custom post type. This code will also include the capabilities added and generated by the plugin. All you need to do is copy this code into your functions.php and before that disable the plugin. So the custom post type stays and now you can play around with the code / capabilities of the custom post type.
stackexchange-wordpress
{ "answer_score": 1, "question_score": 3, "tags": "custom post types, plugins, user roles, security, capabilities" }
Escaping html for meta description I am using this code to add to my posts a meta description from a custom field. $des = get_post_meta( get_the_id(), 'fl_description', true); if( ! empty( $des ) ){ $meta_des = esc_html($des); echo '<meta name="description" content="' . $meta_des . '" />'; However, I need to completely escape all html tags and shortcodes. i.e the input <p><span class="x-dropcap">D</span>esigned by interior mastermind Chams it is one of the only top <strong>members</strong> clubs where partying and dining co-exist under one roof. </p> needs to become: Designed by interior mastermind Chams it is one of the only top members clubs where partying and dining co-exist under one roof.
To strip HTML tags and shortcodes, use a combination of PHP's strip_tags ( < ) and WordPress's strip_shortcodes ( < ) $meta_des = strip_shortcodes( strip_tag( $des ) );
stackexchange-wordpress
{ "answer_score": 0, "question_score": 0, "tags": "php, escaping" }
Include post_date in search I'd like to search posts by year. For example, I could type in "June 2015" and all posts from that time appear. Or, I could type "2015" and all posts from the year appear. Currently, I have Relevanssi set to index all public posts and attachments, including all categories and tags. Yet, posts from a searched time (ex, "2015") are not populating, unless the term is in the title or post content. I can't seem to find a solution anywhere. Hoping for some help!
I was able to receive the solution from the developer. Add the below code into functions.php and then rebuild the Relvanssi index. This worked for me. function rlv_index_post_date( $content, $post ) { $date = get_the_time( "F Y", $post->ID ); $content .= " $date"; return $content; } add_filter( 'relevanssi_content_to_index', 'rlv_index_post_date', 10, 2 );
stackexchange-wordpress
{ "answer_score": 0, "question_score": 0, "tags": "plugins, posts, search, date, date time" }
Can't login after URL change I changed the settings first, then relocated WP to another location. Now I can't access `wp-admin` > ERROR: Cookies are blocked or not supported by your browser. You must enable cookies to use WordPress. Database should have been updated successfully, as I updated the fields in Settings before I relocate WP. I tried to manually define URLS in `wp-config.php` as explained here: < but didn't help. What else can I try?
Looks like the issue was because of Nginx or other caching server. Rebooting the server solved the issue! There was nothing more to do in the database or `wp-config.php`
stackexchange-wordpress
{ "answer_score": 1, "question_score": 2, "tags": "login, cookies" }
<!--nextpage--> and previews I am trying to preview my blog post that has `<!--nextpage-->` but clicking on any of the other pages just brings back to the home page. There was an old thread that never got resolved 4 years ago < The URL when I do a preview looks like this ` All well and good, but once I click on a page this happens: ` Note that the page number gets injected after `?p=1569` like `?p=1569/2/&preview...` if it was decoded.
There's a bug regarding _content pagination_ links not working when previewing _scheduled_ posts or pages. See ticket #32295 There's already a proposed patch that adds the missing `future` status check within the `_wp_link_page()` helper function, that generates the content pagination links. We could e.g. construct a quick-fix like: add_filter( 'preview_post_link', function( $link, $post ) { if( ! is_admin() && is_preview() && 'future' === get_post_status( $post ) ) $link = preg_replace( '~p=(\d+)%2F(\d+)%2F~', 'p=$1&page=$2', $link ); return $link; }, 10, 2 ); or use the `wp_link_pages_link` filter: add_filter( 'wp_link_pages_link', function( $link, $i ) { if( $i > 1 && 'future' === get_post_status( get_the_ID() ) && is_preview() ) $link = preg_replace( '~p=(\d+)%2F(\d+)%2F~', 'p=$1&page=$2', $link ); return $link; }, 10, 2 );
stackexchange-wordpress
{ "answer_score": 2, "question_score": 3, "tags": "previews, nextpage" }
Can't see login page after migration I already have an existing website on live server. I want to setup on local machine. Following Steps has been taken: 1. Download whole website 2. Place whole code under `htdocs/mywp` 3. Change the database file. replace all link from ` to ` (my local IP) 4. Import the database and change the `wp-config` file 5. Deleted .htaccess file Now, when I visit: ` The page load except for the styling (CSS). When I try to visit: ` It doesn't open it redirects to: ` Can anybody tell me what steps can be taken?
Sounds like you are still having content pointing back to your live URL, possibly. To ensure that you have changed all the URLs from ` to ` follow these steps: 1. Go and download Interconnect IT's Database Search & Replace Script here 2. Unzip the file and drop the folder in your **localhost** where your WordPress is installed (the root) and rename the folder to **`replace`** (screenshot) 3. Navigate to the new folder you created in your browser (ex: ` and you will see the search/replace tool 4. It should be pretty self-explanatory up to this point: enter your old URL in the **`search for…`** field and the new URL in the **`replace with…`** field You can click the _dry run_ button under _actions_ to see what it will be replacing before you execute the script. Once you're done be sure to remove the `/replace/` folder.
stackexchange-wordpress
{ "answer_score": 0, "question_score": 2, "tags": "plugins, wp admin, migration, localhost" }
can't delete a row from post_meta table I have checkbox in my post and I want to delete a database row when checkbox is not checked but when I press update button nothing happend and the row wasn't deleted. here is my codes if (isset($_POST['save-author-to-book'])) { $key = 'save-author-to-book'; $values_to_save = array(); $new_values = $_POST["save-author-to-book"]; $existing_values = get_post_meta( $post_id, $key, true ) ; if(!empty($new_values)){ foreach($new_values as $new_value ){ $values_to_save[] = $new_value ; } update_post_meta( $post_id, $key, $values_to_save ); } } else{ delete_post_meta( $post_id, $key, $meta_value=''); // break; } any idea would be appreciated.
This is because the value of meta **key** is inside the if clause and is not set for the else. try else { $key = 'save-author-to-book'; delete_post_meta( $post_id, $key, $meta_value=''); // break; }
stackexchange-wordpress
{ "answer_score": 0, "question_score": 0, "tags": "php, database, mysql, sql" }
Parse error after modifying the template menu I made an edit in the template's `functions.php` and now I can't access my website. I know I have to fix the problem from the Cpanel but I'm now scared to do anything because I've tried once and the screen started flashing. This is the error I get: > **Parse error** : syntax error, unexpected '<' in `/.../wp-content/themes/oblique/functions.php` on _line 291_ Is there anyone that can help me with this?
Do you have the original copy of the theme's `functions.php` file? Replace it in order to restore access to your website. But, as the error indicates, you have an unexpected `<` in your code on **line 291**. This means that there was an extra character added that wasn't necessary and throws off your code. Open the `functions.php` file from your theme located in `/wp-content/themes/oblique/` on a text editor that support your text editor (Notepad++, Sublime Text, etc.) scroll down to that line number and you should see the issue. Below is an example of a textpad with line numbers to give you a better visual: ![Sublime Text](
stackexchange-wordpress
{ "answer_score": 0, "question_score": 1, "tags": "functions, themes, errors, parse" }
Search engine for themes I'm looking for a good search engine for WordPress theme. Do you know one? I know Themeforest but we can not add filters to our search... I don't know if my question respect your qualities but I don't know where can I find a response...
Which filter do you need? With Envato you can filter for keywords, software version, categories, etc. Maybe try here on Template Monster.
stackexchange-wordpress
{ "answer_score": 1, "question_score": -3, "tags": "themes, search, search engines" }
Wordpress converts media extention URL automatically to video player I am new to Wordpress, learning one by one everyday. I am having little problem in posting. When I add URL's in content which ends with .mp4 .wmv .mkv or any media related extension. It turns into video player automatically after posting. The browser displays video player instead of plain URL's. How to disable this feature? I dont want any web player for my URL's. Just plain URL link which I set to clickable. I am using Customizr child theme. The same happening in other themes too. Please help and Thank you.
You should consider using the Auto-embeds Disabler plugin here: < Note that it's actually just a single line of code, if you prefer to add that to your functions.php - but I'd suggest keeping it as a plugin so you can easily activate/deactivate that functionality. remove_filter( 'the_content', array( $GLOBALS['wp_embed'], 'autoembed' ), 8 ); Note that WordPress should only be automatically converting URLs, but NOT links. If you create an actual link to the media item, WordPress should display it as a link as opposed to an embedded player.
stackexchange-wordpress
{ "answer_score": 0, "question_score": 1, "tags": "functions, urls, media, embed" }
How to customize default wordpress search query I want to customize default search query in wordpress I want search default data in another database. Now I have 2 databases , one for wordpress and another base with copy of wp_posts content. I want to change search query to secondary database. How to do it via function?
I believe you are looking for this $mydb = new wpdb('username','password','database','localhost'); $rows = $mydb->get_results("select Name from my_table"); echo "<ul>"; foreach ($rows as $obj) : echo "<li>".$obj->Name."</li>"; endforeach; echo "</ul>";
stackexchange-wordpress
{ "answer_score": 0, "question_score": 0, "tags": "search" }
Unable to retrieve any child terms using get_terms For some reason I'm not able to retrieve any child terms for the `carabana_cat` taxonomy. Here's what I've done so far: $custom_terms = get_terms( 'carabana_Cat', array( 'hide_empty' => false, 'orderly' => 'description', 'child_of' => 28) ); What am I doing wrong here? There are lots of child terms for `id=28` which aren't showing up.
Try relying on the new WP_Term_Query() class, here's an example per your code: // WP_Term_Query arguments $args = array( 'taxonomy' => 'carabana_Cat', 'hide_empty' => false, 'orderby' => 'description', 'child_of' => 28) ); // The Term Query $term_query = new WP_Term_Query( $args );
stackexchange-wordpress
{ "answer_score": 0, "question_score": 0, "tags": "terms" }
How to update the options table for a widget Each widget has a row in the `options` table with values for title and other fields. Is there any way we can update those values outside the `update` function? For example, here are some values for a sample widget: a:2:{i:2;a:23:{s:5:"title";s:19:"Widget Title";..... now I want to update the `title` to another value in the `function widget($args, $instance)` and save the value to the database. I found that options API can handle something like this, but I am not sure if this is the correct way and how to update the info for that specific widget. // Update the value of an option that was already added. update_option( $option, $newvalue );
An array will be serialized when saved to the DB. If you want to update a key to the array, you need to * Fetch the option first * Apply modifications * Update the option with the updated array values so in your example if you fetch the option, you should get a multidimensional array where you have a key => value of `[title] => Widget Title` you would update that `title` key with your new value and then update back your option. Something like this $my_option = get_option( 'your_option_name' ); now let's say your key is in the first dimension of the array, then you update your value there. $my_option['title'] = 'New Widget Title'; and finally you update your options back to the DB. update_option( 'your_option_name', $my_option );
stackexchange-wordpress
{ "answer_score": 0, "question_score": 0, "tags": "widgets, database, options" }
Custom plugin settings: clicking "save changes" does not display success message I don't entirely understanding how to save my plugin's settings properly. When I click on the " _Save Changes_ " button it saves data but it does not show any successful like message. Do I need to add an extra function or something else? My form look like this: function bdthemes_core_settings_page() { ?> <div class="wrap"> <h1>BdThemes Settings</h1> <form method="post" action="options.php"> <?php settings_fields("section"); do_settings_sections("plugin-options"); submit_button(); ?> </form> </div> <?php }
I had the same issue as you did, but I found how to fix it in this tutorial: < Basically, I had my settings page outside of the Settings menu, so I had to explicitly add `settings_errors()` to my options page and they started working. :) Hope that helps.
stackexchange-wordpress
{ "answer_score": 5, "question_score": 3, "tags": "plugins, plugin development, admin, options, settings api" }
How should you hook a session_start() when authoring a plugin? Learning more about sessions I've gathered that a `session_start()` should come directly after `<?php` per Where exactly do I put a SESSION_START? and I wanted to play around and create a plugin that would add a `session_start()` to `header.php` after it's `<?php` but after searching I've been inclusive with trying to figure out the appropriate procedure to do this. I did search for session but I've seen a variety of Q&As that mostly seem to use: * `init`: Session is not starting * `wp_head`: Hook into wp_head(); in a plugin * `wp_loaded`: Getting headers already sent error from plugin So when authoring a plugin that relies on session to be added to header.php what is the appropriate hook for adding `session_start()`?
There is no regular output and hence no header sent before `template_redirect` on the front end. If you need sessions on the back end too, use the action `wp_loaded` to cover both. Example: add_action( 'template_redirect', function() { $status = session_status(); if ( PHP_SESSION_DISABLED === $status ) { // That's why you cannot rely on sessions! return; } if ( PHP_SESSION_NONE === $status ) { session_start(); } $_SESSION[ 'foo' ] = 'bar'; }); Keep in mind that using sessions adds a whole set of very complex problems to your code, including security, scalability (load balancers), and following time consuming support issues. I don't recommend it.
stackexchange-wordpress
{ "answer_score": 4, "question_score": 5, "tags": "plugin development, hooks, session" }
By having WordPress in a subfolder does it mean more script executions? By having WordPress installed in a subfolder / directory does this mean WordPress will do more script executions then having WP installed at the root level? **Edit:** The root level index file has 645 563 number of executions while the sub directory index file has 34 739
Short answer, **no**. Having your WordPress site installed in a sub-directly (ex: ` does not mean it will do more script executions then having it installed at the root level.
stackexchange-wordpress
{ "answer_score": 1, "question_score": 1, "tags": "scripts" }
Get image attachment to a post outside the loop? What's the best way to display the URL to an image that's attached to a post and is outside the loop? This is the code I'm using to display the results: <?php foreach($duplicates as $postID) { ?> <?php $postData = get_post( $postID );?> <?php if(esc_html(get_the_category($postID)[0]->slug) == 'group-a-first'):?> group a first (only) - <?php print $postData->post_title;?><br> <?php endif;?> <?php } ?> I was able get results using `<?php print wp_get_attachment_image_src( get_post_thumbnail_id( $postID ), 'thumbnail' )[0];?>` but it works only if a post has a featured image.
try using get_attached_media function and your current `$postID` $images = get_attached_media( 'image', $postID ); this will return a WP_Post object. If you want to get the url, it's located in the `guid` key of the object. Use a foreach loop to retrieve them all. foreach( $images as $image ){ $src[] = $image->guid; } To use a different size image, try foreach( $images as $image ){ $src[] = wp_get_attachment_image_src( $image->ID, 'thumbnail' )[0]; }
stackexchange-wordpress
{ "answer_score": 1, "question_score": 0, "tags": "attachments, images" }
Resetting AUTO_INCREMENT primary key I have a table with a primary key used as a foreign key in another table, now when I delete the entry the primary keys do not stay in order and I want to reorder them and also want to maintain integrity of foreign key
ALTER TABLE tablename AUTO_INCREMENT = 1 Change 1 to your desired value. for that case prior to execution of this you can sort your table with the primary field and get the highest value.
stackexchange-wordpress
{ "answer_score": 0, "question_score": 0, "tags": "plugins, plugin development, mysql" }
Links in new menu don't work My links in navigation don't work if they're not exactly some menu from Admin Panel. Why? On my website < everything is working. I created a new page and a new template page - < . In template page I changed: 'theme_location' => 'main_nav' to: 'theme_location' => 'outpage_nav' and added this menu in functions.php Everything is ok for now. So now I assign new menu in wordpress admin panel to this outpage_nav. Menu is visible properly but we can't click on any link. The same bug is with every other menu I have in Admin Panel - footer menu etc. Only fully working menu is original main menu visible on homepage which I've got from developer who did the original template. Any ideas what's wrong?
You have a script active that prevents normal behaviour of links if they have no `target="_blank"` attribute on them. The original site has this attribute on the link to the blog, so that one works. The 'new' site doesn't have it on the menu links, so those links are disabled. To fix this, go to the menu section in admin. In your screen option, make sure that you can edit the target on links. Change accordingly. Note that this means every page of your site will be opened in a new window, which is not very user friendly. Changing the script would be better.
stackexchange-wordpress
{ "answer_score": 0, "question_score": 0, "tags": "menus, jquery, admin, navigation, links" }
Display image file size in media library This wonderful answer to a related question; that of displaying dimensions in the media library. display image size in media library screen is it possible to use this technique to display the file size as a column? If so how?
In your theme's `functions.php` add the following code to get the file size for all of your items in the _Media_ library: add_filter( 'manage_upload_columns', 'wpse_237131_add_column_file_size' ); add_action( 'manage_media_custom_column', 'wpse_237131_column_file_size', 10, 2 ); function wpse_237131_add_column_file_size( $columns ) { // Create the column $columns['filesize'] = 'File Size'; return $columns; } function wpse_237131_column_file_size( $column_name, $media_item ) { // Display the file size if ( 'filesize' != $column_name || !wp_attachment_is_image( $media_item ) ) { return; } $filesize = filesize( get_attached_file( $media_item ) ); $filesize = size_format($filesize, 2); echo $filesize; }
stackexchange-wordpress
{ "answer_score": 8, "question_score": 2, "tags": "media library" }
Add a Custom Permalink option in the Permalink Admin Screen? My plugin has several custom post types and the main one I want to make its permalink slug changeable. I would prefer to keep things clean and add that option in WordPress' Permalink admin screen, below category base and tag base. How can I hook into that though, I can't find anything but I know it's possible (Woo does it, amongst others)? ![enter image description here](
To hook your custom plugin settings into the Permalink settings, use the following: add_action('admin_init', 'wpse_237141_custom_permalink_section'); function wpse_237141_custom_permalink_section() { add_settings_section( 'your_custom_id', // ID 'Your Plugin Settings', // Section title 'your_callback', // Callback for your function 'permalink' // Location (Settings > Permalinks) ); } You'll need to fill in the blanks to display your own custom functions, but this will now display your settings in the _Permalinks_.
stackexchange-wordpress
{ "answer_score": 2, "question_score": 2, "tags": "plugins, plugin development, permalinks, theme options, settings api" }
Include template if a post is a single product I am trying to use `include` to display my plugin template if a post is a single product define( 'WCT_DIR', plugin_dir_path( __FILE__ ) ); add_filter( 'template_include', 'wdm_load_template', 99); function wdm_load_template($template) { $template_slug = basename(rtrim( $template, '.php' )); if( ($template_slug === 'single-product' || $template_slug === 'woocommerce') && is_product() ) { $template = WCS_DIR . 'includes/wcs-templates.php'; } return $template; } It's returning the correct path to my plugin template file but its still showing the "single-product" template instead of my plugin template.
As Andy mentioned, you're calling `WCS_DIR`, but that doesn't exist. Updated the code to call `WCT_DIR` instead: define( 'WCT_DIR', plugin_dir_path( __FILE__ ) ); add_filter( 'template_include', 'wdm_load_template', 99 ); function wdm_load_template( $template ) { $template_slug = basename( rtrim( $template, '.php' ) ); if ( ($template_slug === 'single-product' || $template_slug === 'woocommerce') && is_product() ) { $template = WCT_DIR . 'includes/wcs-templates.php'; } return $template; }
stackexchange-wordpress
{ "answer_score": 0, "question_score": 0, "tags": "custom post types, templates" }
Navbar- disable "onClick" drop-down I'm working on a project on my desktop for a theme development, but an issue I am having is that when the user clicks on the navigation menu, it causes it to collapse. Since I got collapse to work on hover, I don't need it when clicked. I'm using the theme Unite. I don't have a way of sharing this project, and only have done surface customizations until the navigation bar. It's all the original PHP and JS. The CSS is original outside of color changes. If someone is able to assist me, I'd be most appreciative!
I think this will work for you demo here is another js solution demo2 $('ul.nav li.dropdown').hover(function() { $(this).find('.dropdown-menu').stop(true, true).delay(200).fadeIn(500); }, function() { $(this).find('.dropdown-menu').stop(true, true).delay(200).fadeOut(500); });
stackexchange-wordpress
{ "answer_score": 0, "question_score": 0, "tags": "theme development, menus, dropdown" }
Creating a Post, can authors be ordered by last name? When I create a post, the author dropdown/select seems to order authors by the first letter of the full display name. Is there a bit of code for functions.php that would order this dropdown by last name?
Here's one example how we can modify the order of users in the dropdowns on the `post.php` and `post-new.php` pages (PHP 5.4+): /** * wp_dropdown_users - modify ordering on post.php and post-new.php */ add_filter( 'wp_dropdown_users_args', function( Array $query_args, Array $args ) { // Nothing to do if we're not on post.php and post-new.php if( ! did_action( 'load-post.php' ) && ! did_action( 'load-post-new.php' ) ) return $query_args; // Modify the user query - Adjust to your needs! $query_args['meta_key'] = 'last_name'; $query_args['orderby'] = [ 'meta_value' => 'ASC', 'display_name' => 'ASC' ]; return $query_args; }, 10, 2 ); Here we query users that have the `last_name` meta key and order first by the `last_name` and then `display_name`. Hope you can adjust it to your needs!
stackexchange-wordpress
{ "answer_score": 1, "question_score": 2, "tags": "posts" }
Advanced Custom Fields - display when specific template used? I know how to display my field groups on specific pages (display location: page is equal to myPage). I have a few different templates on my site and would like to display Field Group X when the page is using template Y. Is this possible?
Hard to give an exact answer without sharing your code, but using `is_page_template()` in an `if` statement will help determine when you display your custom field group: if ( is_page_template( 'template-y.php' ) ) { # Display Field Group X code here... } else { # Do something else... } Again, if you could provide your code, I can give you a better answer.
stackexchange-wordpress
{ "answer_score": 3, "question_score": 1, "tags": "templates, page template, advanced custom fields" }
Upload 3 different featured image sizes to Wordpress Is there a way that on Wordpress I can upload 3 different image sizes of my featured image? My post images are a different size in the first column rather than the second column, and I also have an owl carousel. In 2 out of the 3 places my featured image for my post gets distorted. So does anyone know how I can upload 3 different image sizes? Here is what my site post layout looks like. As you can see at the top I have an owl carousel, in column 1 I have one post, and in column 2 I have three posts. ![enter image description here](
I believe you are looking for `add_image_size`. You need to put this into your **_functions.php_** to register new image sizes. WP will automatically crop/resize the uploaded images to fit the sizes you have registered with `add_image_size` _NOTE_ Images that already have been uploaded won't be affected by adding `add_image_size` **only new uploads will**. To overcome this without having to manually upload all images again, use a plugin like Force Regenerate Thumbnails that will recreate the images with all registered sizes done with `add_image_size` Here's how to use it in it's most basic form, keeping the original ratio (no cropping, no distortion) add_image_size( 'custom-size', 220, 180 ); Check out the link to the codex to learn more on how you can use the available parameters.
stackexchange-wordpress
{ "answer_score": 2, "question_score": 2, "tags": "post thumbnails, images" }
Check if user is admin by user ID Any ideas how to check if user ( **by user ID** ) is administrator? I don't mean currently logged in user.
You worded it as you want to check if user has administrator _role_. It is considered more proper to check for _capability_ , relevant to specific action. In practice this is usually expressed as `current_user_can( 'manage_options' )` for current user. For arbitrary user it would be `user_can( $user_id, 'manage_options' )`. Of course this is capability that stands for general configuration of the site. Depending on your purpose you might want to use a different one, see list in roles and capabilities documentation.
stackexchange-wordpress
{ "answer_score": 20, "question_score": 10, "tags": "wp admin, users, user roles, user meta" }
plugin active error hi i installed instagram auto poster on my website by it cant be activated because this error : Parse error: syntax error, unexpected '[', expecting ')' in /home/agahiir2/domains/talarwp.com/public_html/wp-content/plugins/instagram-auto-poster/instagram-api/Instagram.php on line 132 but this error is not from plugin because i installed and activated on another website successfully without problem just has error on my website i deactived some plugins on my website but its still has problem also i checked functions.php on my theme several times and it seems good!!! i really need to fix this problem and active this plugin please help me
As Omar Soliman suggests, > Your host should be running PHP 5.4+ to use shorthand arrays.
stackexchange-wordpress
{ "answer_score": 2, "question_score": 0, "tags": "plugins" }
How to create a subcategory to a PAGE on WP? I have a URL: www.example.com/banana-lp and I want to change it's URL to www.example.com/lp/banana I have been searching for how to do this everywhere but only found how to get this done by "posts" and not "pages".
There is very simple way to do this: 1. Make a page with slug 'lp' or whatever you want 2. Then create page with slug 'banana' and set the previously created page 'lp' as it's parent from the parent dropdown list. 3. Do the same process for other pages whom you want to display like 'lp/otherpages' You can also add category support for pages via coding but I think the above points will solve your problem.
stackexchange-wordpress
{ "answer_score": 2, "question_score": 0, "tags": "categories, pages, directory, sub menu" }
How to change a column width on WooCommerce orders page (Admin) I am trying to increase the column width for 'Ship to' in WooCommerce plugin orders page (Admin). So far, I have tried adding the CSS rules in header as well as I have tried JS solutions but nothing works. Here is the `td` I'm trying to modify: `<td class="shipping_address column-shipping_address" data-colname="Ship to">` Can anyone please help me where is the template for orders listing page in WoCommerce WordPress plugin? I want to add the rules directly in the template file. Any help will be greatly appreciated.
To set a different column width for the _Ship to_ , add this to your `functions.php`: add_action( 'admin_head', 'wpse_237354_ship_to_column' ); function wpse_237354_ship_to_column() { global $pagenow; if ( $pagenow == 'edit.php' ) { ?> <style type="text/css"> .manage-column.column-shipping_address { width: 10px; } </style> <?php } } This adds custom CSS in the header page with your new column width. Just change `width: 10px` to your new size.
stackexchange-wordpress
{ "answer_score": 1, "question_score": 1, "tags": "woocommerce offtopic" }
How to apply an ID to Shortcode Embedded iframe I want to add an `id="myid"` to shortcode embedded iframe:- $video_url = get_post_meta($post_id, 'video_url',true); //or $video_url .= 'video url'; $check_embeds=$GLOBALS['wp_embed']->run_shortcode( '[embed]'. $video_url .'[/embed]' ); echo $check_embeds; This code helps me to display video through custom meta box just using a video url. And additionally I want add an ID to iframe here, example:- `<iframe id="myid" src=""></iframe>`like this. Can anybody help me to fix the issue?
1.- Add this to your child theme's functions file: add_filter("embed_oembed_html", function( $html, $url, $attr ) { if ( !empty( $attr['id'] ) ) { $html = str_replace( "<iframe", sprintf( '<iframe id="%s"', $attr['id'] ), $html ); } return $html; }, 10, 3); 2.- Now use `[embed id="myid"]` applying the ID attribute in the shortcode. $check_embeds=$GLOBALS['wp_embed']->run_shortcode( '[embed id="myid"]'. $video_url .'[/embed]' ); Hope that helps.
stackexchange-wordpress
{ "answer_score": 0, "question_score": 1, "tags": "shortcode, embed, youtube, oembed" }
Social icons on my index page don't take visitor to specific site(s) **My index page** has three button on top upper right corner. They are Facebook, Twitter and RSS. I have accessed my `header.php` to add the appropriate URL's for both Facebook & Twitter (I did not add RSS feed as of yet) below is a screenshot of what I have so far: ![screenshot]( However, the icons aren't going to the appropriate URL, why is that?
Per the OP's answer that was posted within the comments: > I went into my `wp-admin`, initially edited in the `header.php` and then updated it. However, they didn't work. While waiting for responses here, I later discovered they did work (about a day later), cannot understand that. This sounds like it was a caching issue which took a day for the results to appear. In the future, be sure to clear the cache in both your web browser and your website to make sure that you changes go through.
stackexchange-wordpress
{ "answer_score": 0, "question_score": 0, "tags": "headers, custom header" }
Wp-theme Development <?php query_posts( array( 'category_name' => 'notice', 'posts_per_page' => 1 ) ); while ( have_posts() ) : the_post(); echo '<h1>','<a href="<?php the_permalink(); ?>">'; the_permalink(); the_title(); echo '</a>','</h1>'; echo '<p>'; the_content(); echo '</p>'; endwhile; wp_reset_query(); ?> When I click this heading, My post not showing on single.php what is the problem? Sorry for my bad English.
Please check how the Loop works, followed by the correct way to instantiate a new Query. Try this: <?php // The correct way to create a new Query $newquery = new WP_Query( array( 'category_name' => 'notice', 'posts_per_page' => 1 )); // Check if query found posts, then start the Loop if($newquery->have_posts) : while ($newquery->have_posts() ) : the_post(); echo '<h1><a href="'.get_the_permalink().'">'.get_the_title().'</a></h1>'; the_content(); // End post iteration endwhile; // If query didnt find any posts else: echo 'No posts in the query'; // End the Loop and reset the query endif; wp_reset_query(); ?> If nothing shows up, you should debug the query with: var_dump($newquery);
stackexchange-wordpress
{ "answer_score": -1, "question_score": -1, "tags": "custom post types, posts, wp query, permalinks, blog" }
wp_query return nothing I have custom post type 'book' and I also make taxonomy name best-book which. I want to filter taxonomy term but it doesn't work. I try to put echo and print_r to find where is my problem and I found that my $loop var return empty array. I also use this style in other pages and never have problem but I can't find why this happen? and how can I have fix it. here is the photo which show it return empty array ![enter image description here]( here is my code <?php $args = array( 'post_type'=>'book'); loop = new WP_Query( $args ); print_r($loop); while ( have_posts() ) : the_post(); $post=the_post(); $term_list = wp_get_post_terms($post_id, 'best-book', array("fields" => "all")); foreach($term_list as $term_single) } ?> any idea would be appreciated.
You need to reference to your query, when starting the loop, otherwise it will show the posts found with the main query, instead of your custom query. Try: <?php $args = array( 'post_type'=>'book'); $loop = new WP_Query( $args ); // Start the loop for your custom query if($loop->have_posts() ) : while ($loop->have_posts() ) : $loop->the_post(); the_title(); // just an example, output what you need here // Get the post terms $term_list = wp_get_post_terms($post->ID, 'best-book', array("fields" => "all")); // Iterate the terms, if found if($term_list) { foreach($term_list as $term_single) { echo $term_single; } } endwhile; // In case the query is empty else: // Debug the query echo '<pre>'; var_dump($loop); echo '</pre>'; endif; ?>
stackexchange-wordpress
{ "answer_score": 0, "question_score": 0, "tags": "custom post types, wp query" }
Replace a menu with widget or a custom template file programmatically I am using the child theme for customization and now I want to replace the **top menu** with a custom widget or a **file that contains custom content** , but the theme does not support hooks, filters and actions, so how do I replace it without modifying core `header.php`? Here is how the top menu being called right now: <?php $main_top = array('theme_location' => 'Top_Menu', 'container' => '', 'menu_class' => 'sf-top-menu', 'menu_id' => 'menu-top', 'fallback_cb' => false);?> <?php if(!of_get_option('disable_top_menu')==1){?> <div class="mainmenu"> <?php wp_nav_menu($main_top);?> <div class="clearfix"></div> </div> <?php }?>
You can modify the arguments passed to `wp_nav_menu` with a filter called `wp_nav_menu_args`. You can use this filter to add a walker class, which will modify the behaviour of `wp_nav_menu`. This approach is kind of hackish, because the walker class will still 'walk' through all the menu items, but you can control them, so decide not to output any item. Here's a nice tutorial on the walker class. Inside your walker class you can include your custom content. Note that you'll need to add `html`, as `PHP` code will not be evaluated anymore.
stackexchange-wordpress
{ "answer_score": 0, "question_score": 1, "tags": "functions, menus, filters, widgets, hooks" }
Add dynamic color to each category item I'm trying to give custom color to each **category item** , But it gives only one style to all items. I use this plugin for the colors: 'Category Color' My code as below, <?php $category = get_the_category(); $the_category_id = $category[0]->cat_ID; if(function_exists('rl_color')) { $rl_category_color = rl_color($the_category_id); } $sep = ''; foreach ((get_the_category()) as $cat) { echo $sep . '<a href="' . get_category_link($cat->term_id) . '" class="' . $cat->slug . '" title="View all posts in '. esc_attr($cat->name) . '" style="background:' . $rl_category_color . '">' . $cat->cat_name . '</a>'; $sep = ', '; } ?>
You are getting the color for one category ( _term_ is more appropriate though) $the_category_id = $category[0]->cat_ID; instead of checking the ID and Color for each term, that's why it's applying the same to all. Try this (untested): <?php $categories = get_the_category(); $sep = ''; foreach ($categories as $cat) { $the_category_id = $cat->term_id; if(function_exists('rl_color')){ $rl_category_color = rl_color($the_category_id); } else { $rl_category_color = '#000'; // maybe a default color? } echo $sep . '<a href="' . get_category_link($cat->term_id) . '" class="' . $cat->slug . '" title="View all posts in '. esc_attr($cat->name) . '" style="background-color:' . $rl_category_color . '">' . $cat->cat_name . '</a>'; $sep = ', '; } ?>
stackexchange-wordpress
{ "answer_score": 1, "question_score": 0, "tags": "plugins, posts" }
Getting image in mail I need to get a post thumbnail to show up in an email, but this doesnt work with just `mailto`: as i've tried it. <a href="mailto:?subject=Anbefalt innlegg - <?php the_title(); ?>&body=Hei, jeg fant et innlegg som jeg tror du vil like. <img src='<?php echo wp_get_attachment_url( get_post_thumbnail_id($post->ID) ); ?>'>"> This only gives me the url, and the img tag doesnt work. Any ideas how to make this work?
The `mailto` protocol is fairly limited and does not support html in the body. Notably iOS supports some tags, but you cannot rely on that. The point is that `mailto` parses information from the browser to the user's email program. The more tags are allowed, the higher the security risk becomes. So, if you insist on sending the mail using the remote mailing program, you're stuck. The alternative is using `wp_mail`. Users could still click on a link, but in stead of to their mailing program, the will be brought to a (popup) page where can send their message. There are many plugins that do this.
stackexchange-wordpress
{ "answer_score": 1, "question_score": 0, "tags": "email, html email" }
Can set_transient() be used in multi-site? I understand that Transients API is used to cache data and should be intended to store data that is expected to expire. **However, please clarify the following.** Can `set_transient()` be used to store data in multi-site scenario? If yes, how is it different from using `set_site_transient()` function?
As the Codex suggests: > Essentially the same as set_transient() but works network wide when using WP Multisite. > > One difference is that the transient name should be 40 characters or less in length. Also, while set_transient() sets transients that have an expiration time to not autoload, all transients added with `set_site_transient` **will auto-load at all times**. In other words, the fundamental difference is in the auto-loading and since transients might be serialized, you could risk breaking things if referring to a blog (in MU) which has different settings/url/etc. **So the short answer is:** * use set_transient for single blogs * use set_site_transient when you need something for ALL blogs. Example of stored transients: ![enter image description here](
stackexchange-wordpress
{ "answer_score": 2, "question_score": 1, "tags": "multisite, transient" }
Theme update deleted my custom page I have a WordPress install on my own server for testing reasons, as I want to use WordPress in professional situations. I used WP before, but that was long time ago and this is the first time I ran in to this. I set up a site with Customizr theme. I made one of the pages use a custom theme I created. I managed to do this by copying my theme file in the Customizr theme folder. When a Customizr update happened it deleted my file. **Is there a way to avoid this to happen or I have to keep it in mind that any custom file will be deleted at every update?** It is problematic, because I think it is good to have up to date files. On the other hand if at every update I have to set up everything again... it just doesn't worth it. **Is there a way to protect files and settings from theme update?**
Yes, any custom file in a theme directory will be deleted at every update. Adaptations to a theme should be in a separate directory according tot the rules for child themes.
stackexchange-wordpress
{ "answer_score": 1, "question_score": 0, "tags": "themes, child theme, updates" }
Show category ID on custom post type I have a clients who's using the WPCasa theme. The theme has a Custom Post Type named `properties` and has categories on it (`for rent`, `for sale`, etc.). My client wants to show the category of the property on it's title (i.e. "For rent - House on Miami Beach"). However, I'm not being able to get it. I'm looking codes and trying all of them, but there's no result. I don't know if it's the codes or I'm not placing it on the right place (I'm doin' it on `functions.php`). If anyone can help me, I would be really thankful. The code I'm trying is this: <? php $terms = get_the_terms( $post->ID , 'custom taxonomy name' ); foreach ( $terms as $term ) { echo $term->name } ?>
> A little clarification: > > * **taxonomy** is a container of terms > * **term** is the classification of an object (post, project, property) > > > "Post Categories" is a taxonomy. The Categories inside are terms. **UPDATE** For single posts: Use the code you posted, in the `single.php` file (or the template file for this custom post type), but you should change '`custom taxonomy name`' to the correct taxonomy slug. You can easily get the slug, by going in the backend, then go in the taxonomy page as you normally would to add more terms. In the url you'll see the slug of the taxonomy after `&taxonomy=` eg. Make sure that it's after the beginning of the loop `if(have_posts()): while(have_posts()) : the_post()` For term pages: Use this code in the taxonomy page (eg. `category.php`, `archive.php` or what your template uses for this taxonomy) global $wp_query; $term = $wp_query->queried_object; echo '<h1>'.$term->name.'</h1>';
stackexchange-wordpress
{ "answer_score": 1, "question_score": 1, "tags": "custom post types, functions, categories, taxonomy" }
Efficient way to check local Wordpress php files and Database for malicious code? First of all, I am not a WP superuser. Recently a friend of mine got hacked, by hacked I mean he didn't update his WP for a long time and got malicious code injected which sent spam, so his hoster blocked him. He only has the infected files, which were already checked and cleaned by a developer...by hand. Now I should setup a new server running his code. But I would like to let a tool check the code of the theme at least and DB. I will setup a fresh installation and re-install the plugins, to make sure that these are free of bad code. So what I have is only the hand-cleaned code, so I don't know what injection we had before, so I can't search for the same pattern or anything. I found some tools, which check the WP-Website for bad code, like sucuri - sitecheck, but this is not an option for me. I would like to check the code locally. What do you guys recommend me to do?
Well if your concern is about the theme and data stored in the database, I suggest you also start with a "new install" of the theme. And as far as the DB goes, I've had a similar experience where I took the hacked DB and installed it on my localhost, then exported the `wp_users`, `wp_usermeta`, `wp_posts`, and `wp_postmeta` tables **ONLY**. Then I did a clean install (on the hosting server) of WP with a NEW DATABASE as well, and imported the `wp_users`, `wp_usermeta`, `wp_posts`, and `wp_postmeta` tables into my clean DB. Typically when a site gets hacked and the DB is affected, it's the `wp_options` table that has problems.
stackexchange-wordpress
{ "answer_score": 3, "question_score": 0, "tags": "wp admin, security, hacked" }
How to add an image to the post preview in the free theme "food recipes" I'm making my first wordpress site. When I publish a post I see it in my home page but despite I add an image I can't see it above the post title in my home page. ![enter image description here]( Thank you in advice.
Based on your question, it's hard to exactly determine when you say: > _...I add an image I can't see it above the post title..._ Also, considering that you said this is your first wordPress site, I am going to assume you added the in **within your Post** and not set it as a **Featured Image** which is what usually determines the image of the post on your homepage. Be sure to do the following: 1. Open your post and on the right hand side, you should see a box label **Featured Image** 2. Click **Set featured image** and choose or upload your image 3. **Update** your post and you should see your featured image on the homepage It should look like the following in your post: ![enter image description here](
stackexchange-wordpress
{ "answer_score": 0, "question_score": 1, "tags": "images, themes" }
List All Post Types in Admin view using /wp-admin/edit.php?post_type= I have successfully created a custom post type. I'm trying to construct a URL which points to a combined listing of posts of all post types on the view all posts page in the admin view. I can construct a URL which points to posts of specific post types, eg ` But I can't find a way of listing posts of all post types. Is it possible to use the `/wp-admin/edit.php?post_type=` slug to point to a page listing posts of all post types? Or, how else can I build a URL which will?
The only way this could work would be `?post_type=any` based on WP_Query post_type params. But the context is the problem, the `edit.php` page requires a specific post type, to display and edit only one $post_type_object which returns, for each post_type, only one singular label, one plural label and so many others individual properties. These are not only technical blocking problems but also conceptual ones which make this impossible to be done. Personally, I would research on "How to build a custom admin page" with a query like `post_type=any`
stackexchange-wordpress
{ "answer_score": 4, "question_score": 3, "tags": "admin, post type" }
Programmatically create and place a nav menu in a theme location? A client has numerous subsites and would like to include a 'global menu' within the packaged theme. I've got a registered location `global-menu` and I've got it populated with links in `functions.php`. Which action do I use to place that menu inside of the theme location?
`wp_nav_menu` displays a navigation menu and `'theme_location'` can target a menu registered with `register_nav_menu`. wp_nav_menu( array( 'theme_location' => 'global-menu' ) );
stackexchange-wordpress
{ "answer_score": 2, "question_score": 1, "tags": "menus, themes" }
Can someone explain why wordpress uses two column for storing time values? I see two table columns in wordpress tables for time values. Examples: `post_date` `post_date_gmt` `post_modified` `post_modified_gmt` `comment_date` `comment_date_gmt` What is the reason behind storing different time types?
The `post_date` is the `post_date_gmt` after the Timezone value (in Settings) has been applied. So, if you like, the reasoning is that there's a _standard time for everybody_ , and then _your own site's time depending on your Settings_ , so say you want to change that later, the _standard time_ is always left untouched.
stackexchange-wordpress
{ "answer_score": 3, "question_score": -1, "tags": "date time, timestamp, timezones" }
How to get sum of meta_values of a meta_key in wp_query according to conditions Here is my query args : $query_args = array( 'post_type' => 'rented_properties', 'post_status' => 'publish', 'order' => 'DESC', // 'fields' => 'SUM(amount_to_paid)', ); $my_querys = null; $my_querys = new WP_Query($query_args); My meta key is `amount_to_paid`, and I want to get the sum all the meta_values of this query condition. Please suggest your answer with `query_args`. My Scenario : I have 1000 posts and each with meta_key amount_to_paid and it has some value. Now I filter 20 posts and want to get sum of meta_value of amount_to_paid . Did you got me now?
`WP_Query` gets posts from the database, but it's not a generic SQL query class, it should really be called `WP_Post_Query`, as `WP_Query` implies it can do any SQL. As a result, you need to do several things: 1. Grab the posts you need 2. Get their meta values for `amount_to_paid` using `get_post_meta` 3. Add those values up using the basic PHP maths `+ - / * = += -=` So: $sum = 0; $query = new WP_Query($query_args); if ( $query->have_posts() ) { while( $query->have_posts() ) { $query->the_post(); // do the processing for each post $sum = $sum + get_post_meta( ... ); } } echo esc_html( $sum );
stackexchange-wordpress
{ "answer_score": 1, "question_score": 0, "tags": "wp query, post meta, meta query" }
How do I make my site publicly viewable? Everything redirects to wp-admin When you do to the website, instead of displaying the pages as normal, it requires the WordPress user to login before viewing the site. No matter what URL I plug in for the site, it always redirects to /wp-login.php. There aren't any plugins installed to prompt this kind of behavior, and nothing in the .htaccess file would either. Any help in resolving this issue would be highly appreciated. Thanks.
The pages are published, and not private. I was quite baffled, because the plugin set is the same as several other sites I'm working with, and this was the only one that was having issues. However, after deactivating the plugins, I noticed that one of them, which requires a license key for updates, hadn't been registered with the key yet, and was horribly out of date. Fixing that fixed the site.
stackexchange-wordpress
{ "answer_score": 2, "question_score": 1, "tags": "login" }
WordPress Add [cdata] to title tag in rss feed i have this feed < and i want to adding [CDATA] to title tag. I try to add this to functions.php but with no luck. add_filter('the_title_rss', 'job_modify_post_title'); function job_modify_post_title ( $title ) { if ( is_feed('job_feed' ) ) { return '<title><![CDATA[' . $title . ']]></title>'; } } Any help? Best Regards, Panagiotis Mitsinigkos
`is_feed()` acept only one parameter to specify the feed type you want to check, like rss, atom, and so on. `job_feed` is not a valid feed type. If you want to modify title of feed posts of some type, something like this should do the job: I think this code should work: add_filter( 'the_title_rss', 'job_modify_post_title' ); function job_modify_post_title ( $title ) { if ( 'your_post_type' === get_post_type() ) $title = '<![CDATA[' . $title . ']]>'; return $title; }
stackexchange-wordpress
{ "answer_score": 2, "question_score": 1, "tags": "rss, feed" }
wp_editor add media button not working I am creating a wordpress plugin(backend activity, form submission) where Instead of inserting plain text, users need to add images and html texts so, I need to use wp_editor instead of form element. code for wp_editor I used below. wp_editor( '', 'instructions', $settings = array('textarea_name' => 'instructions', 'textarea_rows' => '5') ); I can see "add media" button but, when I click on it, nothing (no media library pop up) appears however, if I go to Posts-> Add a new post and over here same the "add media" button poping up media library normally, where user can insert or select already uploaded image files.
I will assume that you are creating a custom admin page at `?page=add-quiz`, in this case before calling the `wp_editor` function you also have to enqueue the CSS / Js files for it with the `wp_enqueue_media()` function. So at the end you should have wp_enqueue_media(); wp_editor( '', 'instructions', $settings = array('textarea_name' => 'instructions', 'textarea_rows' => '5') ); A clever way to do it would be inside an action like function prefix_my_custom_admin_scripts() { wp_enqueue_media(); } add_action('admin_enqueue_scripts', 'prefix_my_custom_admin_scripts'); Again assuming that you don't have this hook already.
stackexchange-wordpress
{ "answer_score": 3, "question_score": 0, "tags": "plugin development, uploads, media library, wp editor" }
Check if I am in the Admin Panel (wp-admin)? I want to have my plugin check if the user is anywhere in the **Admin Panel** (`wp-admin`) before executing a script. This would include: /wp-admin/ /wp-admin/edit.php?post_type=page /wp-admin/themes.php etc. Similar to using the using the `global $pagenow`: global $pagenow; if ( $pagenow == 'upload.php' ) { # do something if in the Media page } From doing some research, it looks like the `get_current_screen()` function is something I need, but this is what I've come up which doesn't work: global $my_admin_page; $screen = get_current_screen(); if ( $screen->id = $my_admin_page ) { return $content; }
You can use the is_admin function. By definition, it checks "Whether the current request is for an administrative interface page." You might also want to verify you are not doing an AJAX call by doing if ( ! is_admin() && ( ! defined( 'DOING_AJAX' ) || ! DOING_AJAX ) ) { # code here... }
stackexchange-wordpress
{ "answer_score": 6, "question_score": 1, "tags": "plugin development, functions, wp admin" }
Include Max mega menu Plugin into theme I want to add the Max Mega Menu plugin into my theme for a project. What i've done: * copy and paste plugin folder into my theme * include `megamenu.php` file into my theme `function.php` file Needed to work: * include with theme * active when theme active So, how can I include this plugin and activate it when my theme is activated?
If you include a plugin directly inside a theme then it will be rejected by both the WordPress.org theme directory and ThemeForest. You should use TGMPA for including plugins with themes: < Further reading: < Using TGMPA means the plugin remains a plugin, WordPress loads it in the normal 'plugin' way, and users will get plugin updates as they're released.
stackexchange-wordpress
{ "answer_score": 2, "question_score": 2, "tags": "plugins, theme development, menus, themes" }
How to check if a hook is hooked or not? For example: if ( is_hooked('hook_name') ) { throw new \Exception('You cannot hook to a protected action.'); } else { do_action('hook_name'); } Is there a way to define the `is_hooked()` function?
Sure, that's called `has_action`, which is an alias of `has_filter`. Usage: if ( has_action('hook_name') ) { throw new \Exception('You cannot hook to a protected action.'); } else { do_action('hook_name'); } These two functions access the global array `$wp_filter` that stores all of the filters / actions
stackexchange-wordpress
{ "answer_score": 4, "question_score": 6, "tags": "filters, hooks, actions" }
Moving jQuery to the footer without using de-register in WordPress Hi I was looking for a way to move wordpress default jQuery to the footer and I saw this answer: < So, I tried this approach in my child theme's `functions.php` file: add_action( 'wp_enqueue_scripts', function() { // Move jQuery to the footer wp_scripts()->add_data( 'jquery', 'group', 1 ); wp_scripts()->add_data( 'jquery-core', 'group', 1 ); wp_scripts()->add_data( 'jquery-migrate', 'group', 1 ); }); But it is not pushing jquery to the footer. Any idea guys why is this happening? I want to avoid the `de-register` & `re-register` way of doing this. Any help will be highly appreciated. * * * **Important Update:** Since WP v3.9 there is no way of putting jquery scripts in your footer rather than using the `de-register` & `re-register` option. It is just simply cannot be done as the author pointed out below.
You should use the param `$scripts` of the hook `wp_default_scripts`. In this hook was en-queued all default scripts, also jQuery and you can change his data, like the group for load in footer. add_action( 'wp_default_scripts', '_print_jquery_in_footer' ); function _print_jquery_in_footer( $scripts ) { if ( ! is_admin() ) $scripts->add_data( 'jquery', 'group', 1 ); } Also in the newer code style via anonymous function, like your question example; possible since php 5.3: add_action( 'wp_default_scripts', function( $scripts ) { if ( ! is_admin() ) $scripts->add_data( 'jquery', 'group', 1 ); } ); **Edit** : This will only work with WordPress versions lower than 3.9!
stackexchange-wordpress
{ "answer_score": 3, "question_score": 4, "tags": "jquery, wp enqueue script" }
How do I query a single data value from the wp_metadata table? I am modifying a search.php template. The basic template displays search results with thumbnail, title, date, and author. I would like to add 2 additional fields from the wp_metadata table. I assume I need to write a function and add it to my child theme functions.php file, then call the function from the template. I just need to know how to correctly write the function.
You need to use `get_post_meta`: > **get_post_meta( $post_id, $key = '', $single = false )** > > Retrieve post meta field for a post > > **$post_id** (int) (Required) Post ID. > > **$key** (string) (Optional) The meta key to retrieve. By default, returns data for all keys. Default value: '' > > **$single** (bool) (Optional) Whether to return a single value. Default value: false eg. echo get_post_meta( $post->ID, 'the-name-of-key', true); When using `true`, you will get a `string`, but if you use `false` instead, you will get an `array`.
stackexchange-wordpress
{ "answer_score": 1, "question_score": 0, "tags": "php, templates, search" }
How to check if a protected hook is hooked? I need to protect some hooks which only can be hooked by functions/callbacks within my theme/plugin. For example: if ( is_protected_hook('hook_name') ) { throw new \Exception('You cannot hook to a protected hook.'); } else { do_action('hook_name'); } Is there a way to define the `is_protected_hook()` function? Any suggestions will be greatly appreciated!
As noted in my answer to your related question there is a datastructre `$wp_filter` that stores all information on hooks and filters. You may want to try a `var_dump` on it just to see what it looks like. There is no built in variable 'protected'. This leaves you with two options to keep the administration of the hooks you want to protect: build it into `$wp_filter` yourself or keep it separate. I recommend the latter. Maintain an array `$protected_hooks`. I don't know the conditions under which you want hooks to be protected, but you will have to set this array the moment you add an action to a specific hook. Now, in your tempate file you will need a double condition: is a hook active and is it protected. That would go like this: if ((has_filter('hook_name') && in_array('hook_name',$protected_hooks)) ...
stackexchange-wordpress
{ "answer_score": 4, "question_score": 0, "tags": "filters, hooks" }
Overwriting the menu break points of twentysixteen in child theme I am currently working on a child theme with TwentySixteen being the parent. Currently in the functions.js file of TwentySixteen, it has a break point of 910 where the normal menu stops and the menu-toggle button displays instead. I need to reduce the width of this down to 810 but am unsure how to do this. Obviously i dont want to touch the TwentySixteen theme files.
Copy the `js` folder of the parent `TwentySixteen` theme to child theme root. Then add the below code in your `functions.php`- function the_dramatist_dequeue_scripts() { wp_dequeue_script( 'twentysixteen-script' ); wp_deregister_script( 'twentysixteen-script' ); } add_action( 'wp_print_scripts', 'the_dramatist_dequeue_scripts' ); function the_dramatist_twentysixteen_scripts() { wp_enqueue_script( 'twentysixteen-child-script', get_stylesheet_directory_uri() . '/js/functions.js', array( 'jquery' ), null, true ); } add_action( 'wp_enqueue_scripts', 'the_dramatist_twentysixteen_scripts' ); Then in your child theme `js` folder (the folder you copied earlier) find the `functions.js` file and make your changes. It will give you the desired output.
stackexchange-wordpress
{ "answer_score": 0, "question_score": 1, "tags": "functions, javascript, theme twenty sixteen" }
Website completely messes up when logging out Alright so the website is completely perfect when I am logged into the WP-ADMIN page but if I log out of there, the website is completely messed up. All the formatting is broken and everything looks weird. You can see it for yourself here: < This is how it looks when logged in: < One thing to note is that /wp-admin suddenly leads to Page not found 404 and that I can only login using /wp-login.php Does anyone know what the problem is behind all of this? This happened all of a sudden, without any update to wordpress. Thank you
If you check out the browser's console, you can see that several stylesheets are not loading. Also, there's this error: Resource interpreted as Stylesheet but transferred with MIME type text/html: "< It appears that you have a plugin installed that does caching/script minification, and something is not configured correctly there. The plugin is probably configured to NOT serve cached pages to logged in users, so that's why it looks fine when you're in the admin area. Disable the caching/script minification plugin, and troubleshoot from there.
stackexchange-wordpress
{ "answer_score": 1, "question_score": 0, "tags": "php, css, html" }
What is the correct way to get only display plugin for Administrator Only Currently I'm a little confused with the usage of `is_admin()` and `current_user_can( 'manage_options' )` What is the right way for it? At this moment I use `is_admin()` to include files for Administrator: if (is_admin()){ //include here };
`is_admin` is true when you're in the dashboard/admin area, aka `example.com/wp-admin`. It asks the question "are we in the admin area?", and is true of anybody logged in and inside the admin area. This could be a user with the role subscriber who sees only the edit profile page. This function is similar to `is_home()` or `is_single()`, and has nothing to do with the current user, only their location on the site. `current_user_can( 'manage_options' )` is true, if the current logged in user has the capability with the name `manage_options`. Normally only administrators have these options. Note that a plugin may change this
stackexchange-wordpress
{ "answer_score": 2, "question_score": 0, "tags": "wp admin, admin" }
ACF - if field has value within Field Group conditional statement I have a field group(product specs) with bunch of sub fields. I want to put the subfields all within a container. Id like a field group if statement, there is none to be found: in docs, on the ACF site and here. Making me think am going about it wrong. I can live with an empty table however it feels so wrong. Thanks for your help. <?php if(get_field_group('field_group_name')) { echo '<table>'; if(get_field('field_name')) { echo '<td>' . get_field('field_name') . '</td>'; } if(get_field('field_name')) { echo '<td>' . get_field('field_name') . '</td>'; } echo '</table>'; } ?>
I posted on ACF site, they were very helpful in finding the solution. if( get_field('field_name') && get_field('field_name')) { } Was that solution I was looking for. I knew it was never asked because it was simple logic :/ Slowly learning as I go. Hope this helps someone.
stackexchange-wordpress
{ "answer_score": 0, "question_score": 0, "tags": "advanced custom fields" }
Get the cart details from the order id in woocommerce? How we can get the complete cart details from the order id in woocommerce including the totals and subtotals etc.
Try this: <?php global $woocommerce; $items = $woocommerce->cart->get_cart(); ?>
stackexchange-wordpress
{ "answer_score": 1, "question_score": 2, "tags": "woocommerce offtopic" }
Can is_page and is_front_page both be true? For some reason `is_front_page` isn't triggered on my subsite, running a child theme with its own header with a page set as a static home page under Reading. I have this code in `header.php` to control which metatags to show on a post/page or on the frontpage, but only the `is_single` / `is_page` is printed. <?php if (is_single() || is_page()) : if ( have_posts() ) : while ( have_posts() ) : the_post(); ?> <!-- this is printed --> <?php endwhile; endif; elseif(is_home() || is_front_page()) : ?> <!--this is not printed --> <?php endif; ?> I was wondering if the `is_page` and `is_front_page` are cancelling each other out since they are both true when using a static front page?
Indeed, if your site has a static page on the front, the condition `is_page` will be true and WP will never get to the `elseif`. If you want a different template for your front page, you should exclude it from the first condition so it will return false in that case. Like this: if ((is_single() || is_page()) && !is_front_page()) Or you can switch the statements around: first test for home/front and if that fails for single/page.
stackexchange-wordpress
{ "answer_score": 1, "question_score": 1, "tags": "multisite, pages, templates" }
wp_localize_script with boolean and init I have problem with `wp_localize_script`, That I cannot get **boolean** and **int** as variable wp_enqueue_script( 'helloworld' , 'helloworld.js', false, '1.0.0', true); $site_config = array(); $site_config['boo'] = (bool)true; $site_config['number'] = (int)1; wp_localize_script( 'helloworld' , 'site_config' , $site_config ); **Why I getting :** var site_config = {"boo":"1","number":"1"}; **Why not :** var site_config = {"boo":true,"number":1}; * Wordpress 4.6 _(latest)_ * PHP 5.6.10 Does not it fixed ? < , I do anything wrong or missing something ?
**I just do something like this so long :** wp_add_inline_script('helloworld','var site_config ='.json_encode($site_config));
stackexchange-wordpress
{ "answer_score": 4, "question_score": 3, "tags": "javascript, wp enqueue script, variables, wp localize script" }
cant enable theme in multisite Has anyone met this problem : When I click `Network enable` on any theme: ![enter image description here]( then after page is reloaded, the same thing happens - the theme is not enabled, and there is still "Network Enable" . I have deleted all plugins, but still same problem.
Finally I've found that, in `wp-sitemeta` DB table, `allowedthemes` record value was incorrectly serialized (dont know why) and there was `a:4` (instead of `a:3`, because actual length of array was: 3 values of **`s:`** ) `a:4:{s:13:"twentysixteen";b:1; s:5:"meris";b:1; s:8:"my_theme";b:1;}` I changed `a:4` to `a:3` and it worked. (also, make sure there is no more `allowedthemes` rows in `wp-sitemeta` table)
stackexchange-wordpress
{ "answer_score": 3, "question_score": 2, "tags": "multisite, themes" }
Placing the_content inside shortcode not working Have placed `<?php echo do_shortcode('[wcm_restrict plans="silver"]' .$the_content. '[/wcm_restrict]'); ?>` into a template, but the content isn't appearing. Have tested `<?php echo do_shortcode('[wcm_restrict plans="silver"]Big Blue[/wcm_restrict]'); ?>` so know the tags are working fine. Also tried `get_the_content` Content appears also when just using `<?php the_content(); ?>` What am I doing wrong?
It doesn't appear that the variable `$the_content` exists. I'm guessing what you want is the function `the_content()`, but since that actually echoes its output, that won't work either. You need to use the function `get_the_content()` which will return the output (as opposed to echoing it). Try this: echo do_shortcode('[wcm_restrict plans="silver"]' . get_the_content() . '[/wcm_restrict]');
stackexchange-wordpress
{ "answer_score": 5, "question_score": 1, "tags": "php, shortcode, templates" }
Add custom content in user-edit.php page When I go to edit a user's account located in: ` I want to add a custom section with my own information (just text), similar to the `add_settings_section()` function. However, I believe this is limited to only adding custom sections to the _Settings_ menu: Settings -- General -- Reading -- Media -- Permalinks This is what I have so far which adds my custom section in the _Reading_ menu for testing purposes: add_action( 'admin_init', 'wpse_edit_user' ); function wpse_edit_user() { add_settings_section( 'user_role', 'User Roles', 'wpse_user_role_section', 'reading' ); } function wpse_user_role_section() { ?> <p class="description">Content to my custom section here...</p> <?php } But I do not want to located in _Reading_. How can I have my custom content display in the `user-edit.php` page?
Solved it by using `show_user_profile` and `edit_user_profile` instead: add_action( 'show_user_profile', 'wpse_237901_user_edit_section', 999 ); add_action( 'edit_user_profile', 'wpse_237901_user_edit_section', 999 ); function wpse_237901_user_edit_section() { # Code here... }
stackexchange-wordpress
{ "answer_score": 4, "question_score": 2, "tags": "wp admin, settings api" }
WooCommerce shipping - Different product different shipping? I'm on WooCommerce Version 2.6.4 and trying to figure out how to set shipping to individual project. We have products come with different weights and sizes. So we want to have different different shipping cost applied to each of them. For instance: **Product A costs £10 and its shipping is £5.** So if you buy **2** of product A, then: 2 X £10 = £20 (cost of 2 items) 2 X £5 = £10 (shipping) If I use the flat rate just as in the guide 5 * [qty] Then this apply to all products. But I have other products, eg **Product B, costs £20, shipping costs £7**. Then how can I do that with that flat rate above?
Create shipping classes for each of your product variations which require one. On your product page, add the attributes for the product, then add the variations, based on the added attributes. Once loaded, you may select the individual product variations to modify price, size, weight, inventory, and shipping class for each specific product variation. **To Setup product variations:** Add a new product. Set product to Variable Product. Select Attribute Tab. Add Attribute Name (in this case I choose "Size") & add Attribute Values (separate values with a pipe) & select "Use for Variation". Save Attributes: ![Add Attributes]( Select Variations Tab & Select "Add Variation" or "Create Variations from All Attributes": ![Add Variation]( Select the variation you'd like to modify the shipping for and adjust shipping. ![Add Shipping](
stackexchange-wordpress
{ "answer_score": 3, "question_score": 1, "tags": "woocommerce offtopic" }
Facebook link to website logo I have someone who wants to share my website through Facebook and they want my logo to appear in the FB post. What do I have to do on the WordPress end to have my logo automatically appear in the FB post?
I'd recommend checking out the following plugins: * Yoast SEO * Open Graph Protocol Framework Either one will take care of all of the Open Graph metadata. Once you have the plugin set up, you can simply go to your homepage and you will see a "Featured Image" widget: !Featured Image Pick your logo and you will see the `og:image` which is what Facebook uses to set the post image. <meta property="og:image" content=" /> ### Update I see that you set up the Open Graph Protocol Framework and now when I visit your website, I see the `og:image` metadata. Here's a preview of what it looks like if I were to share it on LinkedIn: !LinkedIn Snippet
stackexchange-wordpress
{ "answer_score": 2, "question_score": 1, "tags": "facebook" }
Get post with multiple meta keys and value I am trying to fetch a post based on the following meta keys. * `post_code` with `432C` * `location` with `XYZ` Both belong to a CPT. I'm trying to fetch the Post with both these meta_values. I Don't Want an OR relation, I want a AND relation, I have tried several `WP_Query` objects and still haven't found a solution after hours of looking.
**SOLUTION** The Solution Accepted below worked, however, I wanted to know how is it working? This is how it's working SELECT * FROM wp_posts p, wp_postmeta m1, wp_postmeta m2 WHERE p.ID = m1.post_id and p.ID = m2.post_id AND m1.meta_key = 'key1' AND m1.meta_value = 'value1' AND m2.meta_key = 'key2' AND m2.meta_value = 'value2' AND p.post_type = 'cpt' AND p.post_status = 'published'
stackexchange-wordpress
{ "answer_score": 1, "question_score": 10, "tags": "custom post types, wp query, post meta" }
How to prevent wp-login brute force attack from thousand of different IP? Investigating a problem. I found out that I had so many calls to `wp-login`, but from many different ip's. Any idea on how to handle it?
Sadly it's not uncommon to receive many rogue login attempts. If you have a strong password policy this actually shouldn't worry you too much. If there is a limited amount of people with logins and they work from fixed addresses, you can block acces to that page by writing a rule in your `.htaccess` that blocks all visitors from `wp-login.php` except those with certain ip-addresses. Also, security plugins like iThemes can track rogue plugin attempts for you, and issue bans as well as fix common security loopholes. But you can't stop people from trying to get in, unless you decouple your site from the internet.
stackexchange-wordpress
{ "answer_score": 2, "question_score": 1, "tags": "security, hacked" }
How to return a blank page I can't seem to figure this out, how do I return a blank/white page in the admin area from a plugin page? Edit: How do I stop the default ui from loading and return an empty body instead?
To return a blank page that's been created in a plugin like so: ### Example: `blank-page.php` <?php // Blank PHP page... Use the following function: add_filter( 'some_tag', 'wpse_238008_blank_page', 99 ); function wpse_238008_blank_page() { // Template with an empty page define( 'PLUGIN_PATH', plugin_dir_path( __FILE__ ) ); return PLUGIN_PATH . '/path/to/blank-page.php'; } Replace the following to suit your needs * `some_tag` \- Name of the filter to hook the function to * `/path/to/blank-page.php` \- Location of your blank page in your plugin Your question isn't very clear when you say: > _...how do I return a blank/white page in the admin area..._ If you can update your question to specify where you want to see this exactly, I can give you an updated answer.
stackexchange-wordpress
{ "answer_score": 0, "question_score": 0, "tags": "plugin development, admin" }
Do not show excerpt in post content I need to keep showing excerpt in list of articles on my index, while, not showing it on single post page. I am using more tag to manually define excerpts. Is there a way to trim excerpt from the post?
Don't use the more tag to manually define excerpts. There's a separate input field for that. If it's not visible, go to "screen options" in the upper right corner of the edit screen to enable it. What exactly is shown on your single and archive pages depends on your theme. There is no general way to address this. But if you use the excerpt field for what it is meant to do, any decent theme will pick it up and display the excerpt on archive pages and the post (where you have removed the excerpt) on the single page.
stackexchange-wordpress
{ "answer_score": 3, "question_score": 1, "tags": "themes, excerpt, single, read more" }
Admin Blank Page with Working Front-End After Updating to Wordpress 4.6 Trying to open my website admin `mywebsite.com/wp-admin` it giving me `internal server error 500` The website working fine from the front end. How can I access my admin and how to solve this issue?
After debugging this problem, I found this error in the PHP error log located at `public_html/mywebsite/wp-admin/error_log`: PHP Fatal error: Call to undefined function wp_raise_memory_limit() in /home/example/public_html/mywebsite/wp-admin/admin.php on line 141 This function `wp_raise_memory_limit()` should be defined in `wp-includes/functions.php` but it is not defined in my case due to an unsuccessful update by Wordpress. **So Solution:** Do a manual update for wordpress as I did the following: * I downloaded the latest version of wordpress from wordpress.org * I replaced all files and folders of my site except `wp-config.php` file and `wp-content` folder * I opened my site url, it requested a database update I pressed on update database and the problem resolved :)
stackexchange-wordpress
{ "answer_score": 4, "question_score": 1, "tags": "wp admin, fatal error" }
How to remove the space before the ellipsis in excerpt? I'm trying to figure out how to remove the blank space the appears at the end `the_excerpt();` before the ellipsis. **As seen here:** ![Random Blank Space]( It doesn't appear to be a part of the ellipsis as I changed `[...]` to `...` using the following code: function new_excerpt_read_more_sign($content) { return str_replace('[&hellip;]', '&hellip;', $content); } add_filter( 'the_excerpt', 'new_excerpt_read_more_sign' ); What's causing the blank space?
Wordpress adds a space when applying the `excerpt_more` filters. Filter the `excerpt_more` to change this correctly. < add_filter('excerpt_more', 'theme_name_filter_excerpt_more'); function theme_name_filter_excerpt_more() { return '&hellip;'; }
stackexchange-wordpress
{ "answer_score": 1, "question_score": 0, "tags": "php, functions, excerpt" }
Is it the right way to add jquery and css in wordpress? function dwwp_admin_enqueue_scripts_mlm() { wp_enqueue_style( 'dwwp-admin-css', plugins_url( 'css/admin-users.css', __FILE__ ) ); wp_enqueue_script( 'admin-users', plugins_url( 'js/admin-users.js', __FILE__ ) ); wp_enqueue_script( 'jquery', ' ); wp_enqueue_script( 'jquery-ui', ' ); wp_enqueue_style( 'jquery-style', ' );} add_action( 'admin_enqueue_scripts', 'dwwp_admin_enqueue_scripts_mlm' );
No. As wordpress codex states, you should use jquery and other javascript files provided by them. As for css files I think you can use yours. Please check this link( scroll down) for a list of already defined javascript files. Also, you have to use local files as much as possible, unless you have no other way. So for example, if you have a js library, you should download it and include it in your theme/plugin files and not enqueue it using CDN or any other external link. Wordpress team will refuse to publish your theme/plugin if you include external js files without a good reason. LE: for jquery-ui you only have to use this wp_enqueue_script( 'jquery-ui') or add it as a dependency of your own script like this wp_enqueue_script('my-script', 'url-to-scrip', array('jquery-ui'))
stackexchange-wordpress
{ "answer_score": 0, "question_score": 0, "tags": "plugin development" }
How to get woocommerce inventory status In a woocommerce theme, Im trying to show a warning when product is out of stock. Something like this: <?php if ('this_product_is_out_of_stock'): ?> <p>This product is out of stock. It can be purchased by custom made order.</p> <?php endif; ?> Is there a function to say 'this_product_is_out_of_stock' or some other way to achieve it? I was searching woocommerce api docs unsuccesfully: < Thank you in advance.
Try something like this global $product; if ( ! $product->managing_stock() && ! $product->is_in_stock() ) echo '<p>This product is out of stock. It can be purchased by custom made order.</p>';
stackexchange-wordpress
{ "answer_score": 18, "question_score": 6, "tags": "functions, theme development, woocommerce offtopic" }
change or add css to theme from plugin I want to add/change the CSS of my current theme from my plugin. I've tried `add_action` and `wp_enqueue_style` and doesn't work My code: function register_plugin_styles() { wp_enqueue_style( 'fh-plugin' , plugins_url( 'nf-plugin/includes/f-hide.css' )); } add_action( 'wp_enqueue_scripts', 'register_plugin_styles' );
I believe you need to add `__FILE__` to your `plugins_url()` function. It may not be calling the right location. It should look like this: add_action( 'wp_enqueue_scripts', 'wpse_238154_register_plugin_styles' ); function wpse_238154_register_plugin_styles() { wp_enqueue_style( 'fh-plugin' , plugins_url( 'nf-plugin/includes/f-hide.css', __FILE__ ) ); }
stackexchange-wordpress
{ "answer_score": 1, "question_score": 0, "tags": "plugins, plugin development, css" }
Find the URL of the current plugin directory So i'm working on a plugin where I assign a default avatar to anyone that comments. The line i'm stuck on contains a theme directory reference but I want to reference the image in the plugin directory instead. Thanks in advance! $new_avatar_url = get_bloginfo( 'plugin_directory' ) . '/avatar-1.jpg';
Try `plugin_dir_url()`: $new_avatar_url = plugin_dir_url( __FILE__ ) . '/avatar-1.jpg';
stackexchange-wordpress
{ "answer_score": 3, "question_score": 1, "tags": "plugins, plugin development, urls" }
How to display warning on post editor when trying to add new term to custom taxonomy? i have a function i use to stop users from adding new terms to custom taxonomies, this is the code: add_action( 'pre_insert_term', 'prevent_terms', 1, 2 ); function prevent_terms ( $term, $taxonomy ) { if ( 'language' === $taxonomy) { return new WP_Error( 'term_addition_blocked', __( 'You cannot add terms to this taxonomy' ) ); } return $term; } This works fine when you are on the custom taxonomy page (/wp-admin/edit-tags.php?taxonomy=language) Because you see the warning. BUT when you try to add a new term by saving a post, you get no warning, the term simply don't get saved. What i need is add a warning to this function so the person saving a post knows he cannot add new terms to this taxonomy. Any way to achieve this? Thanks.
Whilst this doesn't show a warning as you are asking for, you could always hide the "add new" link using the admin_head action: function yourprefix_admin_head() { echo '<style> #language-add-toggle { display: none; } </style>'; } add_action('admin_head', 'yourprefix_admin_head'); The element ID is the taxonomy name followed by `-add-toggle`. This is enough for most cases, unless you think your users are a bit devious. Hope it helps.
stackexchange-wordpress
{ "answer_score": 7, "question_score": 4, "tags": "custom taxonomy, editor, warnings" }
Can I set a timer for pages to be published? I have a page that's in draft mode right now because I want to publish this on a particular day (sometime this week). Is there a way that I can set a timer/countdown for this page to automatically be published on a day that I choose? I don't want to manually publish this page as I want this up at 12:00 AM and I don't want to wake up in the middle of the just to do that... Is there some sort of script I can run to do this?
No script of function necessary. It's actually built into WordPress. Simply go to your page to edit and on the right hand side you should see a widget labeled _Publish_. On the third line down, you will see an _Edit_ button and you can set the date and time on when you want the page to be shown: !Publish
stackexchange-wordpress
{ "answer_score": 3, "question_score": 1, "tags": "pages, publish, draft" }
Providing updates to your Wordpress theme I've been doing a lot of research but can't find a straightforward way to provide updates to a Wordpress theme. I have a custom theme I created for my blog and would like to provide updates to it from time to time. How should I go about this? Btw, I don't want the theme to be public.
Here is an tutorial about wordpress automatic update link and if you want to update it from github link I think you will find your answer there just follow the instructions.
stackexchange-wordpress
{ "answer_score": 0, "question_score": 0, "tags": "theme development, themes, child theme" }
Does Wordpress not use relative URLs? The articles/posts I've read about migrating Wordpress between local/staging/live servers talk about having to migrating the URLs each time - is this true? Or can you simply switch Wordpress to use relative URLs? Sorry if this is basic but hard-coded URLs make no sense so thought I'd check before following bad advice.
Out of the box Wordpress uses absolute URLs. This requires you to make database updates when moving sites from development to production or when changing the base URL. I'm not sure why this choice was made but there are many options when moving sites. 1. You can use a tool like WP Migrate DB Pro or another option that will work with serialized data to change the URL in the database after moving. 2. Another option seems to be a plugin that changes that URLs to relative ones. It is up to date but I haven't used it so I can't endorse it. (<
stackexchange-wordpress
{ "answer_score": 2, "question_score": 4, "tags": "customization, development strategy" }
How to use my menu PHP code as sidebar? I'm using the Max Mega Menu plugin. The plugin gives me a `PHP Function` for my menu. But the plugin has no documentation on how to use it. I want to add the menu as a sidebar to the left of my existing contents. What should I do next? Should I just copy the php code to `sidebar.php` in Wordpress? What am I supposed to do with the PHP code? How to use it in my sidebar? ![enter image description here](
wp_nav_menu is a standard WordPress function, so you would just copy/paste that PHP code into `sidebar.php` using whatever additional arguments you need. However, since the theme has a `sidebar.php` it probably has widget areas, so I would look in `Appearance > Widgets` in the dashboard and look for a sidebar widget area. In there, I would create a textarea widget into the sidebar widget area and copy/paste the **shortcode** into that widget. It should then render the menu in the same way as the PHP code.
stackexchange-wordpress
{ "answer_score": 3, "question_score": 0, "tags": "plugins, menus, css, sidebar" }
Pagination issue with tag.php I use this code in `tag.php`: global $wp_query; $paged = (get_query_var('paged')) ? get_query_var('page') : 1; $termsss = $wp_query->queried_object; $my_argsss = array ( 'post_type' => array('pavilion','post','catalog','tenders','services'), 'tag' => $termsss->slug, 'posts_per_page' =>'20', 'paged' => $paged ); $wp_query = new WP_Query(); $wp_query -> query ($my_argsss); if ( $wp_query->have_posts() ) { while ( $wp_query->have_posts() ) { $wp_query->the_post(); // your code! } } At first page, we can see every we want, but in another page returns 404 not found! Any idea?
Never re-do the main query. Hook into `pre_get_posts` and _change_ it. The following needs to go in your `functions.php` (putting in the template will mean it runs too late): add_action( 'pre_get_posts', function ( $wp_query ) { if ( $wp_query->is_main_query() && $wp_query->is_tag() ) { $wp_query->set( 'posts_per_page', 20 ); $wp_query->set( 'post_type', [ 'pavilion', 'post', 'catalog', 'tenders', 'services', ]); } }); And now your template code should just be: if ( have_posts() ) { while ( have_posts() ) { the_post(); // your code! } }
stackexchange-wordpress
{ "answer_score": 1, "question_score": 0, "tags": "templates, pagination, query, tags" }
Print post data inside loop using theme content template I am writing a plugin where I need to display the post data inside the loop using the theme content template in a page. It will be a similar page to the author profile page that displays a list of posts but with my own wp_query. I am currently using the following code- while( $wp_query->have_posts() ) : $wp_query->the_post(); get_template_part( 'content', get_post_format() ); endwhile; but the problem is this works for some theme and some not. In some theme they don't output anything. Is there any way so I can make it work on all theme or at least maximum theme?
Every theme is different - there is no standard way of naming (or even using) a template part. You would be better off using your own markup and default styles, but allow theme authors to override it with hooks & filters.
stackexchange-wordpress
{ "answer_score": 0, "question_score": -1, "tags": "wp query, loop, get template part" }
WP Paths in a Plugin - how to include I'm working on my first WP plugin, and I'm having trouble getting a file include to work. My directory structure looks like this: * myPlugin * classes * templates * css * js * myplugin.php My main plugin file (`myplugin.php`) includes / requires various files in the classes directory, and that works fine. However, one of the files in the classes directory is _supposed_ to include a file from the templates directory. I've tried everything I can think of, from `plugins_url()` to `plugin_basename()` to `plugin_dir_path()` but nothing seems to work. How should this statement look to get it to do what I'm trying to accomplish?
Put this in the main plugin file (`myplugin.php`): defined( 'MY_PLUGIN_URL' ) || define( 'MY_PLUGIN_URL', plugin_dir_url(__FILE__) ); defined( 'MY_PLUGIN_PATH' ) || define( 'MY_PLUGIN_PATH', plugin_dir_path(__FILE__) ); right before any other code, and use `MY_PLUGIN_PATH` to include files, or `MY_PLUGIN_URL` to load your assets. E.G: * `require_once MY_PLUGIN_PATH . 'templates/se.php';` * `wp_enqueue_style( 'my-css', MY_PLUGIN_URL . 'assets/css/style.css' );` Those constants can be accessible from any other file including the main plugin loader file and the files within the sub-directories. As long as the plugin is loaded correctly. Hope that helps.
stackexchange-wordpress
{ "answer_score": 3, "question_score": 1, "tags": "plugins, paths" }