INSTRUCTION
stringlengths
11
999
RESPONSE
stringlengths
0
999
SOURCE
stringlengths
16
38
METADATA
dict
Testing Plugins for Multisite I have recently published a WordPress plugin and it works great on single sites. I was informed that the plugin is not working correctly on multi-site installations and I understand a few of the reasons why. I have updated the code and need a way to now test my updated code before going to a live customer's multi-site installation. I have a single site installation of WordPress setup for testing purposes but need to test on a multi-site installation. From what I can find the only way to do this would be to setup an entire multi-site installation with at least two sites on the network to test my plugin. Is setting up an entire multi-site installation of WordPress the only/preferred way for plugin developers, or is there a quicker testing environment available.
I've used several popular plugins on my multisite without problems. The only issue I had was when I found that a plugin wasn't working on a sub-site like I thought it should. Turns out that was my fault - the plugin wasn't activated/enabled on that sub-site. Doh! But it all depends on how the plugin is written, and how it is expected to work on a site. Most plugins, as Tom J Nowell stated/implied, should work just fine on multisite and sub-sites.
stackexchange-wordpress
{ "answer_score": 0, "question_score": 0, "tags": "plugin development, multisite, testing" }
How to append_contents using WP_Filesystem? I have scenario that appends the contents into the files, I was using normal file system function of `PHP` Now I have decided to use WordPress `WP_Filesystem` but I cannot see any methods of it which do append the contents into the files. It has only the `put_contents()`, Is there any way to append the file content using WordPress's FS?
`WP_Filesystem` abstraction is primarily meant for performing plugin/theme/core updates, especially in environments with restricted writes. As such it doesn’t really implement full range of possible file operations, as you noted there is no ability to write to the end of file in declared API. More so some possible implementations (depending on file system) might not even be _capable_ of writing to the end of file. In a nutshell you’ll have to take care of this logic yourself and it would depend a lot on it being private/public code and how widely compatible you want it to be. If you stick with `uploads` destination in WP context it has the maximum chances of being writable with direct filesystem access (which WP core itself still uses for many operations).
stackexchange-wordpress
{ "answer_score": 3, "question_score": 2, "tags": "wp filesystem, filesystem api" }
detect screen width in functions I am finding a way to add _A_ before the menu if we are on desktop and to add _B_ if we are on mobile device. As such, this is are my functions for _A_ and _B_ : add_action( 'wp_head', 'A_function' ); function A_function() { //add A } add_filter( 'wp_nav_menu_items', 'B_function', 10, 2 ); function B_function() { //add B } I know I need to put these hooks in functions file but I don't know the way to do it, I know we can use `wp_is_mobile()`. How can I achieve that?
According to codex, `wp_is_mobile();` is a boolean function that returns true if the user is visiting the website on a mobile device, so what you need is: if ( wp_is_mobile() ) { // Run this only for mobile visitors add_filter( 'wp_nav_menu_items', 'B_function', 10, 2 ); function B_function(/* add B */ ); } else { //If we are not on mobile, then run this filter add_action( 'wp_head', 'A_function' ); function A_function(/* add A */); }
stackexchange-wordpress
{ "answer_score": 0, "question_score": 1, "tags": "mobile" }
Default Nav Highlight I'm using the built-in menu functionality `wp_nav_menu` in my project: joshrodg.com/polio/, all of the posts (< < etc.) don't belong to any of the items in the navigation bar (they are not listed in the navigation bar), therefore none of the links in the navigation bar get highlighted when the posts are being shown. I was wondering if there was a way to choose a default item (Home) that could be highlighted in the event that a particular post or page doesn't have their own navigation item...that way something in the navigation bar is always highlighted. Thanks, Josh
Assuming you are loading a single piece of content like one Post (unlike the homepage where you're combining multiple Pages with JS), something like this should do it: <script type="text/javascript"> $(document).ready(function(){ // get each menu item var hasHighlight = 0; // loop through to see if any have "current_page_item" class $("#nav ul li").each(function(obj) { if($(this).hasClass("current_page_item")) { hasHighlight++; } }); // if none of the items are highlighted using "current_page_item" class if(hasHighlight == 0) { $("#nav ul li:first-child").addClass("current_page_item"); } })(jQuery); </script> Enqueue this sitewide so that anytime there is a menu with id "nav" it will check and add a highlight to "Home" if nothing is highlighted.
stackexchange-wordpress
{ "answer_score": 1, "question_score": 0, "tags": "functions, menus, themes, css, navigation" }
Update all posts in a loop everyday Im new to wordpress and I want to try out how to make all the posts therein a wordpress site update everyday with a loop every minute or so. I haven't done anything yet. I just want to know if its possible or is there any other approach I could start on. Many thanks!
Yes, WordPress has a cron system called WP Cron (which is not the same as a *nix cron). The idea is that your plugin would register a task (a WordPress action callback) that performs the desired logic (in your case, running the code that updates all the posts).
stackexchange-wordpress
{ "answer_score": 1, "question_score": 0, "tags": "posts" }
Check IF category_description exists How I can check if `category_description()` exist? I need to just echo it when it exist..
You've answered your own question. if (category_description($category_id)) { echo category_description($category_id); } <
stackexchange-wordpress
{ "answer_score": 3, "question_score": 0, "tags": "categories" }
Insert post's category name into thumbnail string Hopefully a simple question. I've added several post thumbnail sizes to functions.php using add_image_size. They are each named exactly like a post category. I would like to find a way of making each post call the specific thumbnail size assigned to it's category. The best way I can imagine doing it is by inserting the category name into the thumbnail string like so: <?php the_post_thumbnail( 'INSERT CATEGORY NAME HERE' ); ?> What could I put in this php string to make it insert the category's name into this? Thank you.
As @belinus mentioned, you can assign multiple categories to a post, so you have to decide which one to pass to `the_post_thumbnail()`. One approach would be to use `get_the_category()`, which returns an array, then grabbing the first result from that function as your thumbnail size: $categories = get_the_category(); $thumbnail_cat = ! empty( $categories[0]->slug ) ? $categories[0]->slug : ''; the_post_thumbnail( $thumbnail_cat );
stackexchange-wordpress
{ "answer_score": 1, "question_score": 0, "tags": "post thumbnails, categories" }
How do I combine these two conditionals? I'm using two conditionals, which I want to combine into one: if ( !is_page(56) ) if ( !is_404() ) { // Do something. } The intent is 'if it's not page 56 or a 404, do something'. I haven't found a way to combine them without it either not working or triggering an 'unexpected '||'' error. I suspect it's because I don't know enough to correctly position the brackets.
Very easy - if ( !is_page(56)&&!is_404()) // Do something. } Regards, Vinit Patil.
stackexchange-wordpress
{ "answer_score": 1, "question_score": -1, "tags": "conditional tags" }
AddThis Plugin adding html comments in P tags I am using a plugin called AddThis on a website at: < With AddThis enabled I am getting some extra P tags in-between the header and the text on the page: `<p><!-- AddThis Sharing Buttons above --></p>`, this adds a lot of extra space and shouldn't be there. *On the homepage it's the space between the Welcome header and the slideshow image. Is there a function or something out there that I could use to find and remove the html comment on the page to eliminate the extra space? I use a plugin called pSquirrel to detect and remove empty P tags, but it won't remove this one (I'm guessing because pSquirrel doesn't think it's empty because of the html comment). Thanks, Josh
I added this to my `functions.php` file, which removes all html comments, which eliminates the issue. I found the solution here: < function callback($buffer) { $buffer = preg_replace('/<!--(.|s)*?-->/', '', $buffer); return $buffer; } function buffer_start() { ob_start("callback"); } function buffer_end() { ob_end_flush(); } add_action('get_header', 'buffer_start'); add_action('wp_footer', 'buffer_end');
stackexchange-wordpress
{ "answer_score": 0, "question_score": 0, "tags": "plugins, comments, tags, html" }
Get Custom Taxonomy ID within loop I can't figure how to get the ID of the custom taxonomy I'm using to loop through the custom post type called "test_values". function prefix_load_term_posts () { $term_slug = $_POST[ 'term' ]; $args = array ( 'post_type' => 'test_values', 'posts_per_page' => 1, 'tax_query' => array( array( 'taxonomy' => 'test_value_category', 'field' => 'slug', 'terms' => $term_slug , ), ), ); global $post; $myposts = get_posts( $args ); ob_start (); foreach( $myposts as $post ) : setup_postdata($post); ?> <?php endforeach; ?> Anyone have any suggestions how to get this taxonomy ID within the loop?
You can try this function `get_term_by($field, $value, $taxonomy, $output, $filter )` or $termID = []; $terms = get_the_terms($post->ID, 'taxonomy'); foreach ($terms as $term) { $termID[] = $term->term_id; } or `get_queried_object_id()`
stackexchange-wordpress
{ "answer_score": 6, "question_score": 5, "tags": "custom post types, php, custom taxonomy" }
Get Sub-Menu Dropdown to Show Over Page Content I'm using the Avada theme and when i recently did an update, my sub-menu did something weird. Take a look at my website. check the secondary navigation ( The one in the light blue that holds the links to "Justice Peace & Integrity", "Congregation Leadership", and "International Committees" ). The first link (Justice, Peace, ...) actually has two pages underneath it so when you hover over the link, you should see the two pages but instead you can only see the top of one link. I applied `position:relative` to the sub-menu class and that made my drop downs appear but it also expanded the background which doesn't look good. Any suggestions on what I could do? I feel like I'm missing something simple.
There is an overflow issue with your menu items. To solve it, head over to `Appearance > Customize` and add this piece of CSS to your custom CSS: .fusion-main-menu{ overflow:visible!important } This will allow your submenu to overlap the DIV while hovered.
stackexchange-wordpress
{ "answer_score": 0, "question_score": 0, "tags": "menus, css" }
Author Box Meta Issues Currently My author Box is hrad code like this → <p> Lorem Ipsum is simply dummy text of the printing and typesetting industry. Lorem Ipsum has been the industry's standard dummy text ever since the 1500s.Lorem Ipsum is simply dummy text. <a href="#"> Read More </a> </p> If I wish to fetch the authors information dynamically then I make these changes → `<p> <?php get_the_author_meta('description'); ?> <a href="#"> Read More </a> </p>` But Unfortunately this portion `<?php get_the_author_meta('description'); ?>` is not able to fetch the author's description. AUTHORS BIGRAPHICAL INFORMATION IS ALSO WRITTEN
`get_the_author_meta('description')` is meant to return the content to a variable. You're looking for the_author_meta() <?php the_author_meta('description'); ?>
stackexchange-wordpress
{ "answer_score": 1, "question_score": 0, "tags": "author" }
Best way to duplicate specific page content across two sites? I have two sites that are both wordpress based but on separate servers. I would like the content of a specific page to be published in a format that can be included into another site's page. Basically I'd like to publish the page as some kind of a feed so another site can pull it in. Example: SiteA.com/about <\- about is a static page. I would like to be able to access this as a feed or something (sitea.com/about/feed) So that on another sites's page, SiteB.com/partners, can pull in the content from siteA. If SiteA updates the content, SiteB would be in sync. Hope this makes sense. I have looked at custom rss feeds but I am not sure if that is the right way to do this. I've looked at quite a few plugins as well but wasn't able to find the right one. I think the right approach would be to add a plugin to SiteA that lets me access that page's content as a feed but I'm open to ideas/thoughts. Thank you,
This is a good use case for the WP REST API. Site A's content is available through the API, so if you know the ID of the page you want to use, you can make a request for the content that way. For example, if your About page has an ID of 2, then hitting ` would return a JSON object with the data for the page. If your page on Site B makes a request to Site A, gets the response, and displays it (without pulling it into Site B's database), then you'll always be getting the latest version of the content. There are some performance issues to look for, since you're making a remote request on every load, but it's possible to cache the response for a period of time and use the cached version to speed up the local page load. I recommend reading through the REST API handbook for more details on how the API works and how to integrate it into a theme or plugin.
stackexchange-wordpress
{ "answer_score": 1, "question_score": 0, "tags": "plugins, rss, feed" }
Just wanted to Pull Author's Link <p> <?php the_author_meta('description'); ?> <a href="#"> Read More </a> </p> I just wanted to pull authors link here "#", but I tried many options such as → get_the_author() the_author_link() the_author_posts_link() All of them are pulling authors name also. Any solution that will help me pull Just the authors link?
If the_author_meta is already working for you, you should be able to use `get_the_author_meta('ID')` to pass with the `get_author_posts_url();` So, like this: <a href="<?php echo get_author_posts_url( get_the_author_meta('ID') ); ?>">Read More</a> Let me know if that works for you!
stackexchange-wordpress
{ "answer_score": 1, "question_score": 0, "tags": "author" }
Use fetch_feed(); Totally Outside of WordPress? I have used `fetch_feed()` many times with WordPress Project. Now I am working on non WP site. So is there way to use `fetch_feed()` totally Outside of WordPress? What **WordPress Core files** should I copied to my workplace?
You can not use directly the wordpress functions by just copying only core files of wordpress. You can refere this link also so you get some hint :- <
stackexchange-wordpress
{ "answer_score": 0, "question_score": 0, "tags": "php, feed" }
Should you manually ping new Wordpress posts? From what I understand, Wordpress will automatically ping new post so they are indexed by search engines. However, I still see bloggers putting out posts about how you should use all of these external pinging sites to get your posts indexed faster. Are those sites necessary? What is wrong with the way Wordpress pings a post?
This is one of those things I tend to call “ritualistic”. Search engines will never explicitly tell you _either_ that pinging does anything or nothing at all. It's there for them to use or do nothing at all about. From my experience semi–active WP site with basic decent SEO setup (such as sitemaps) would be scanned daily anyway. If your content is _extremely_ (to the hour) time sensitive you could consider going extra mile to make sure about pings to _relevant_ services. Outside of that it’s not typically (in my experience) something that time gets spent on.
stackexchange-wordpress
{ "answer_score": 1, "question_score": 0, "tags": "publish" }
404 Template customization | Want 10 recent Post on the 404.php error page apart from the error Notice I have created a 404 error template. whose main portion looks like this → <div class="main col <?php post_class(); ?>"> <h2>Sorry Boss! This Page doesn't exist.</h2> </div> And the above works quite well. see here a page that doesn't exist. Apart from this error notice I was trying to show top 10 recent posts. so I was trying use the WP Loop → <?php if ( have_posts() ) : while ( have_posts() ) : the_post(); > <?php get_template_part('content','home'); ?> <?php endwhile; ?> <?php endif; ?> perhaps there should be some other way to achieve this, but I want that this template should be used → `<?php get_template_part('content','home'); ?>` so that I can get 10 posts.
The Loop just outputs what is contained in the Main Query, it doesn't fetch any posts on its own. The Main Query is empty on a 404, so there's nothing for The Loop to output. If you want additional content, you have to query for it yourself: $query = new WP_Query( array('posts_per_page' => 10) ); if ( $query->have_posts() ) : while ( $query->have_posts() ) : $query->the_post(); get_template_part('content','home'); endwhile; endif;
stackexchange-wordpress
{ "answer_score": 2, "question_score": 0, "tags": "loop, templates, get posts" }
How to change the wp-login.php page title? I've been using the `document_title_parts` hook to change the page title for some front end pages. However, this doesn't seem to work for the login, register and password management pages. How can I change the wp-login.php page `<title>`?
It looks like it's not easily accessible as it's displayed as src: <title><?php echo get_bloginfo( 'name', 'display' ) . $separator . $title; ?></title> where the separator is: $separator = is_rtl() ? ' &rsaquo; ' : ' &lsaquo; '; and the `$title` part comes from: login_header( $title = 'Some title' , ... ); But it looks like you've already checked this out, as I see you've filed a ticket #40812 for an extra filter to change the _separator_. A workaround that comes to mind, to change the _separator_ , would be to use _output buffering_ hacks to replace it.
stackexchange-wordpress
{ "answer_score": 4, "question_score": 5, "tags": "php, filters, login" }
Remove inline css added by wp_add_inline_css I am creating a child theme. I noticed my parent theme is adding some inline CSS in its functions.php: wp_add_inline_style( 'persona-style-css', $custom_css ); Since I cannot change some values there, is it possible to dequeue it? I have tried to dequeue it using `wp_dequeue_style ('persona-style-css')` but it didn't really help. Thanks in advance.
If `wp_add_inline_css` is fired within an action you can use `remove_action` with the same parameters. You also might use `wp_enqueue_scripts` action to dequeue any scripts or styles in a proper way. But, inline style are not included in the `$wp_styles` global, you can unset them with the action `print_styles_array`, you need to know the handle name to unset it. Hope it gives you some hints to make it works.
stackexchange-wordpress
{ "answer_score": 2, "question_score": 4, "tags": "wp enqueue style" }
How to modify URL (add GET values) after front end form submission? I have coded a form into a WordPress theme. Everything is working fine, except the form data will re-submit when a page is refreshed. Obviously, I need to make some change in URL in order to fix it. I am trying to add something like `?submission=success` in the URL, which I will use as a condition to display a success message or load form. How can I add this to URL?
try this : // constructing URL $url = add_query_arg(["submission" => "success"]); // redirection wp_redirect($url); exit();
stackexchange-wordpress
{ "answer_score": 0, "question_score": 1, "tags": "php, url rewriting" }
Show product information on right side I'm working on this website which uses woocommerce. As I've added a product it's featured image and gallery image shows on the left side but the product details are not on the right but they are shown below the gallery images. Here are some screenshots: ![enter image description here]( In the image above you can see black space on the right. The content that is supposed to be shown here is in the picture below:![enter image description here]( is the link to this page: < Now if I zoom out the page using my browser zoom it goes to the right. So I understand this has something to do with responsiveness of this website but the client has this 13" MacBook and I'm not a coder. So can anyone tell me how to get this done? I can insert the code in style.css or custom .css section the theme options have provided.
You have to chave line number 12557 in your style.css. Go to your style.css file and search for the code bellow and delete it. .woocommerce #content div.product div.images, .woocommerce div.product div.images, .woocommerce-page #content div.product div.images, .woocommerce-page div.product div.images { width: 50% !important; } Is your theme really responsive? I think your theme have a big issue with responsive.
stackexchange-wordpress
{ "answer_score": 1, "question_score": 0, "tags": "css, woocommerce offtopic" }
Gravity Forms Anchor only on Front Page? I have a front page that is pretty long length-wise so I have enabled `add_filter("gform_confirmation_anchor", create_function("","return true;"));` in my `functions.php` file. This helps the Gravity Form return to form on validation or submission (which overrides the defaults which would normally just return you to the top of the page). I am looking for a way to only execute this code on the front page...this is what I have tried (in my `functions.php` file): if (is_front_page()) { add_filter("gform_confirmation_anchor", create_function("","return true;")); } But that continues to add the filter on every page...could anyone point me in the right direction? Thanks, Josh
I found the answer here: How to create a plugin that only operates on the home page? I just had to wrap the filter in a function: function gravity_forms() { if (is_front_page()) { add_filter("gform_confirmation_anchor", create_function("","return true;")); } } add_action('template_redirect', 'gravity_forms'); Thanks, Josh
stackexchange-wordpress
{ "answer_score": 1, "question_score": 0, "tags": "plugin development, filters, frontpage, plugin gravity forms" }
How to give titles to custom post type as "unique" incremental number? I have a custom post type called 'Customers'. Data is taken using a front end form, which is then saved into the post type. But I want the titles to be automatically generated as unique incremental numbers. Meaning, it will go as 1,2,3,4.. I got most of this figured out, except a small issue. If there are no posts, then the new title will be 1. If there are posts, then code will fetch the most recent one, check it's title and generate new title by increasing it by 1. So far so good. But if I delete the most recent post, new post added after that will be assigned same title # as the last one. Also, if I delete all posts, titles will start again from #1. I don't want any of the titles to repeat, no matter if any or even all of previous posts are deleted. I want them to always be go on incrementing, never assign the same # again.
The method for increment you used will not achieve what you want to if you delete the posts. Instead you can save the counter in wp_options table on front-end form submission, something like: if(get_option('customers_count')){ $count = get_option('customers_count', true); update_option('customers_count', $count+1); } else { /** This will automatically add the option if it does not exist. **/ update_option('customers_count', 1); // adding first time as value 1 } It will always take new number as post title #. **Note** : Make sure you update option only when submit form for adding a new post and not for edit post.
stackexchange-wordpress
{ "answer_score": 1, "question_score": 0, "tags": "title" }
How to get post from pure frontend AJAX (using only post ID)? I need to show the various content of a post in a modal overlay. How do I call Wordpress through AJAX from the front end (directly from a .js file), using the classic jQuery method? $.ajax({ 'url' : ? data : { 'id' : 247 <-- post ID } ... }); This is NOT a PHP file, so no: `admin_url('admin-ajax.php?action=my_action&post_id='.$post->ID.'&nonce='.$nonce);` Or?
You can output your javascript via `wp_add_inline_script()`. This way you can set the post's id and AJAX URL before outputting the code: wp_add_inline_script('my-js', ' jQuery.ajax({ \'url\' : '.admin_url('admin-ajax.php?action=my_action').' data : { \'id\' : '.get_the_ID().' } });'); Note that you need to hook to an existing js file to be able to add inline script, so `my-js` must be a valid enqueued script.
stackexchange-wordpress
{ "answer_score": 0, "question_score": 0, "tags": "ajax, front end" }
Variation Swatches for WooCommerce - too many variations I have an issue with Variation Swatches for WooCommerce. My client needs for an item (t-shirt) to have 3 attributes fields. 1. Top material (17 materials - image) 2. Bottom material (17 materials - image) 3. Size (4 sizes - dropdown) Example - top material (material A) + bottom material (material B) + size (XL) Now the issue is that there will be too many variations and possibilities. I know that I can change the number, but there will be memory issues. What is the best way to deal with this issue? ![enter image description here](
Since price depends on the size, and there are four sizes, you will just need four variations: 1. Any Top Material, Any Bottom Material, L 2. Any Top Material, Any Bottom Material, M 3. Any Top Material, Any Bottom Material, S 4. Any Top Material, Any Bottom Material, XL This will let you select any combination of material and change the price depending on the size selected.
stackexchange-wordpress
{ "answer_score": 1, "question_score": 0, "tags": "woocommerce offtopic" }
Post status doesn't update to 'future' every time? My plugin is on two wordpress sites. The 'main' site sends a post to the child site. The child site receives the post via request to admin-post.php and inserts it as scheduled(future) to be published after some time with new title. Everytime the 'process' works, post is received and inserted, the title is changed BUT... not everytime the post is set as scheduled. Like 30-40% of the cases, the post just gets 'published'. It's weird and I don't know how to track this down and what causes it...? Here's the sample code for receiving and inserting posts: $post = array( 'post_title' => $newTitle, 'post_date' => date('Y-m-d H:i:s', strtotime('+30 seconds'), 'post_date_gmt' => gmdate('Y-m-d H:i:s', strtotime('+30 seconds'), 'post_content' => $_POST['post_content'], 'post_status => 'future' ); wp_insert_post( $post )
Why you want to set status as 'future' and publish is in next 30 seconds? I think that time is the issue. You can try some additional time like 5 minutes to publish post after insert, which may improve percentage of accuracy.
stackexchange-wordpress
{ "answer_score": 1, "question_score": 0, "tags": "plugins, posts, plugin development" }
Remove Title of youtube video How can i put a youtube video on my post without show the default title from youtube? I tried to put this code in the theme´s functions, but not worked. function remove_youtube_controls($code){ if(strpos($code, 'youtu.be') !== false || strpos($code, 'youtube.com') !== false){ $return = preg_replace("@src=(['\"])?([^'\">s]*)@", "src=$1$2&showinfo=0&rel=0", $code); return $return; } return $code; } add_filter('embed_handler_html', 'remove_youtube_controls'); add_filter('embed_oembed_html', 'remove_youtube_controls'); Someone can help? Thanks
Update: Try this one.. it works for youtube url in your post which is converted to iframe by wordpress. function remove_youtube_controls($code){ if(strpos($code, 'youtu.be') !== false || strpos($code, 'youtube.com') !== false){ $return = preg_replace("@src=(['\"])?([^'\">]*)@", "src=$1$2&showinfo=0&rel=0", $code); return $return; } return $code; } add_filter('embed_handler_html', 'remove_youtube_controls'); add_filter('embed_oembed_html', 'remove_youtube_controls');
stackexchange-wordpress
{ "answer_score": -1, "question_score": 1, "tags": "title, youtube" }
How to add a rewrite endpoint to unattached media? I'm trying to add an endpoint to unattached media items. This is what I hope to achieve: example.com/attachment-slug/foo/ ...where `foo` is the endpoint I'm trying to add. Here's my code: add_action( 'init', function() { add_rewrite_endpoint( 'foo', EP_ATTACHMENT ); } ); add_action( 'template_redirect', function() { global $wp_query; if ( ! isset( $wp_query->query_vars['foo'] ) ) { return; } include dirname( __FILE__ ) . '/my-template.php'; exit; } ); This doesn't seem to work because when I visit example.com/attachment-slug/foo/ I get a 404. How can I add an endpoint to unattached media?
`EP_ATTACHMENT` will insert rules for things attached to posts (and custom post types), but not unattached media. You can make this work by adding it to `EP_PAGES` instead- add_rewrite_endpoint( 'foo', EP_PAGES );
stackexchange-wordpress
{ "answer_score": 1, "question_score": 0, "tags": "php, url rewriting, endpoints" }
How to resolve Warning: Missing argument 2 for ufwp_widget_text () I am using the edume theme of online courses and when making a purchase of a course from my website give the following error. How could it solve? Warning: Missing argument 2 for ufwp_widget_text() in /home/basic340/public_html/wp-content/plugins/wp-udemy/includes/widgets.php on line 63 Warning: Missing argument 3 for ufwp_widget_text() in /home/basic340/public_html/wp-content/plugins/wp-udemy/includes/widgets.php on line 63
You can set `WP_DEBUG` to `false` in your wp-config.php file. **This won't fix the problem** however It will only hide **ALL** the errors generated by it and any other plugins. The warnings mean the second and third parameters in the `ufwp_widget_text()` function have no defaults set. If you are using this function in your own code be sure to pass all three arguments. If you are not, you will want to make sure the plugin is up to date; it's possible the error was already fixed by the developers. If the issues still persists you can reach out to the developers to report your issue report the issue on the plugin's github repo.
stackexchange-wordpress
{ "answer_score": 1, "question_score": 0, "tags": "warnings" }
Is there a way to change and hide the RSS Feed permalink? Right now my RSS Feed is at /feed/. It redirects to Feedburner fine. What I would to is change the /feed/ link to something only I knew that I could share directly with Feedburner. 1- I still need to have an RSS feed. 2- I need to change its permalink. Is this possible?
Look at this article: < for details on how WP does feeds. Scroll down to the "Customizing feeds with filters and hooks" section for a list of hooks to use for various functions. Lots of good info in that article. Once you figure out what you want to modify, place the appropriate functions in your Child Theme's `functions.php` file. (It is not recommended to modify your theme's `function.php` file, as any changes you make will get overwritten on the next theme update.)
stackexchange-wordpress
{ "answer_score": 0, "question_score": 1, "tags": "rss" }
The Thumbnail aspect Ratio Issue I have used thumbnail like this in my wordpress theme's one template → <?php the_post_thumbnail( 'medium' ); ?> In the browser it is rendering like this → <img width="300" height="220" src=" class="attachment-medium size-medium wp-post-image" alt="" srcset=" 300w, 640w" sizes="(max-width: 300px) 100vw, 300px" > My first question is how to put height = auto is there any function that can help us to achieve this? such as `responsive-img` In short, I am asking should I control the width through the CSS or WordPress gives some function to do this?
If you want to remove the height value from your img URL, you can use this function: add_filter( 'post_thumbnail_html', 'remove_thumbnail_height', 10, 5 ); function remove_thumbnail_height( $html, $post_id, $post_thumbnail_id, $size, $attr ) { $html = preg_replace( '/height=\"\d*\"/', "", $html ); return $html; } This will replace the height with an empty value. Note that you can't use `Auto` as a value for the `height` property. It won't be validated by w3 validator. However, you can set the height to auto in your CSS: .wp-post-image { height: auto; }
stackexchange-wordpress
{ "answer_score": 1, "question_score": 2, "tags": "post thumbnails" }
How to inject attributes into get_the_post_thumbnail? I need to manipulate the `<img>` string returned by `get_the_post_thumbnail()`. I know I can add the `$attr = "stuff here"`. But how do I inject the source for the full size image into the one of the smaller sizes `('thumbnail', 'medium')` strings. I get this (simplified): <img src="url/to/thumbnail_image" /> And need to end up with this (simplified): <img src="url/to/thumbnail_image" data-zoom-image="url/to/large/image" /> I've tried to inject the larger images source path by trying to concatenate strings ... $large_image_url = the_post_thumbnail_url( 'full' ); get_the_post_thumbnail( $the_post_id, 'medium', $attr = 'data-zoom-image=' . $large_image_url . '' ); But it gets stripped out. Anyone fought this before? **NOTE:** I intentionally left out the wrapping quotation marks, as WP doubled them ... so that part of the output is working just fine.
You need to use `get_the_post_thumbnail_url` (the one you're using `echo`'s the URL). get_the_post_thumbnail( $the_post_id, 'medium', [ 'data-zoom-image' => get_the_post_thumbnail_url( $the_post_id, 'full' ), ]);
stackexchange-wordpress
{ "answer_score": 1, "question_score": 1, "tags": "post thumbnails" }
How to remove this function from the homepage? I've added the following function (copied from a website) which displays the date and time of the latest post/page update on every post/page. It works great, but I'd like to prevent it from displaying on the homepage. Please help. function wpb_last_updated_date( $content ) { $u_time = get_the_time('U'); $u_modified_time = get_the_modified_time('U'); if ($u_modified_time >= $u_time + 86400) { $updated_date = get_the_modified_time('F jS, Y'); $updated_time = get_the_modified_time('h:i a'); $custom_content .= '<p class="last-updated">Last updated on '. $updated_date . ' at '. $updated_time .'</p>'; } $custom_content .= $content; return $custom_content; } add_filter( 'the_content', 'wpb_last_updated_date' );
Use `is_front_page()` and bail at the start of the function if true: function wpb_last_updated_date( $content ) { if ( is_front_page() ) { return $content; } // Rest of your function }
stackexchange-wordpress
{ "answer_score": 3, "question_score": 2, "tags": "php, functions, homepage" }
Setting up Version Control for Wordpress plugin development Does anyone have suggestions for setting up version control for developing WordPress plugins? I'm working in a development environment, and I'm trying to avoid having to repo the entire WordPress instance. My ideal solution, is to create a repository for one individual directory that contains my plugin. What are others using to manage their plugin development? Thanks for the advice!
I personally set up a development environment as a base of my WordPress Development, where I've dummy data and some other debugging plugins. I then create my own plugin directory and do `git init` _in it_. During plugin development, I set up the Developer plugin to _Plugin for a self-hosted WordPress installation_. It helps me to understand my plugin's performance with other plugins and themes. Then I add my test data specific to that plugin, develop it, test it, finalize it - `git commit`. For Git remote, I use Bitbucket and Gitlab for private plugins, and Github for public plugins. When the plugin is ready to deploy, I then test it in other development environments similar to this, with other engines (if possible). Finally release the version `git tag -a v1.0.0`. This setup helped me to use a single/duo Development environment for all types of development. And other environments for testing.
stackexchange-wordpress
{ "answer_score": 2, "question_score": 0, "tags": "plugin development, version control, workflow" }
image srcset returns false I have a custom post type. Inside loop of single post template I'm trying to show a featured image with custom `srcset` attribute. My image sizes are: add_image_size( 'i600', 600 ); add_image_size( 'i1000', 1000 ); add_image_size( 'i1200', 1200 ); add_image_size( 'i1800', 1800 ); I'm trying this: $img_id = get_post_thumbnail_id($post->ID); $img_src = wp_get_attachment_image_url( $img_id, 'i1200' ); $img_srcset = wp_get_attachment_image_srcset( $img_id, array( 'i600', 'i1000', 'i1200' ) ); `$img_src` returns right URL but `var_dump($img_srcset);` returns `false` Why `$img_srcset` is returning false? ### Aditional info `wp_get_attachment_metadata( $img_id )` returns: < WP 4.8
First, as birgire said, notation was wrong. Second, I read here that "image sizes matching the aspect ratio for the original image will be returned". So, this is a good behavior for me. I don't need customize srcset anymore.
stackexchange-wordpress
{ "answer_score": 0, "question_score": 1, "tags": "custom post types, post thumbnails" }
Combine WPCLI commands for plugin installation and activation? Instead of running the command for plugin installation and then the command for activation: sudo for dir in /var/www/html/*/; do cd "$dir" && wp plugin install elementor anywhere-elementor wordpress-seo wordfence contact-form-7; done sudo for dir in /var/www/html/*/; do cd "$dir" && wp plugin activate elementor anywhere-elementor wordpress-seo wordfence contact-form-7; done Can one combine both the install and activate to one command?
> Can one combine both the install and activate to one command? It looks like you're looking for this _plugin install_ option > [`--activate`] > > If set, the plugin will be activated immediately after install.
stackexchange-wordpress
{ "answer_score": 1, "question_score": 0, "tags": "wp cli" }
Tweak Meta for Post to work it for Pages also I'm trying to register the metaboxes for both posts and pages. This code registers meta only for posts. Can someone guide me how to accomplish this? (keeping the fact in mind that i want "LESS IS MORE" code attitude) function add_custom_meta_box() { add_meta_box("demo-meta-box", "Option Page to select Page Template", "klogeto_template_option_meta", "post", "normal", "high", null); } add_action("add_meta_boxes", "add_custom_meta_box"); I simply added this: add_meta_box("demo-meta-box", "Option Page to select Page Template", "klogeto_template_option_meta", "page", "normal", "high", null); It has created the option in the back-end, but it can't save the Options. Here is the source to the full code I'm using.
There is a line in the code reference, which is used to save the meta values: $slug = "post"; if($slug != $post->post_type) { return $post_id; } This will simply end the function if you are not on a post. To allow saving data on a page, use this instead (remove the `$slug`): if('post' != $post->post_type || 'page' !=$post->post_type) { return $post_id; }
stackexchange-wordpress
{ "answer_score": 1, "question_score": 1, "tags": "custom field, metabox" }
How Can I Add OnClick Event To A Specific Wordpress Menu Link I need to add the following: onclick="goog_report_conversion('tel:800-123-4567')" To a specific menu link being generated by WordPress. How can I achieve this? Thanks.
This is not really a WordPress specific question, but since WordPress does not provide customization for menu items, I think you're gonna need this. You can use `.bind()` in jQuery to add an event to user's click on an specific item. Take a look at this: jQuery(document).ready(function(){ jQuery( "#menu-item-57" ).bind( "click", function() { goog_report_conversion ('tel:800-123-4567'); }); }); Change the `menu-item-57` to whatever ID of the menu item you want to bind a click event to.
stackexchange-wordpress
{ "answer_score": 1, "question_score": 1, "tags": "javascript, google analytics" }
Output JSON object with woocommerce products My client needs to produce a Json file with all the latest products, so it can sync with a external site, whenever there are changes in the data -products- it is updated immediately. They requested to have a daily update with new products, I have never used the REST Api, how can I achieve this? Also they have mentioned that it could work with a XML file, one named products.xml with all products and a updates.xml file with all the new products that have been added to the site, I'm not sure which solution could be easier to get working. Could they just feed from the Sitemap.xml ? I appreciate any hints.
I don't know if you still need this, but maybe someone else will. WooCommerce already has a REST API that's very flexible. For your request you can simply create a API Key and use it to interogate the whole list of products. Since newest products beeing added with higher ID's they should see the latest products in the feed in real-time (carefull with the requests, it can break your server if you do too many). Here is how you create the keys in order to authenticate the feed then following this example you can list all the products. Finally you should have an URL like this: The consumer_key and consumer_secret gets replaced with the ones you generated in the Wordpress Admin and the domain changes to yours. Please do keep in mind that for this to work you need the REST API Enabled `WooCommerce > Settings > API`, usually this option comes checked by default.
stackexchange-wordpress
{ "answer_score": 2, "question_score": 1, "tags": "woocommerce offtopic, json, rest api, xml" }
WordPress hook for visiting a post I am very new to WordPress plugin development. I have been searching this for a quite a while now but I am currently creating a plugin and I need my plugin to start logging the amount of views a post has had. I already know what I want this part of to do however I am having trouble find out how to a PHP function for when a post is viewed by a visitor to my WordPress site. Could someone please show me what the WordPress hook/event is to run a function on post view/load? I want to do this without the use of template as well.
I assume you are looking for a conditional to check if you are on a post page. You can do so by using `is_single()`: if (is_single()) { // Update your post views here } If you insist on using filters or hooks, you can use `the_content` filter: add_filter( 'the_content', 'update_post_views' ); function update_post_views($content){ if (is_single()) { $id = get_the_ID(); // Now update your post's views } return $content; }
stackexchange-wordpress
{ "answer_score": 5, "question_score": 2, "tags": "plugins, plugin development" }
Order list woocommerce Orders based on meta for custom status I'm trying create custom status called "Priority Order" when the product change status to "Priority Order" will automatically add post meta called `_priority_list` numeric based on how much orders set to priority orders, my questions is how to make default order list using meta `_priority_list`? here is my current code: function filter_priority_orders() { global $pagenow; $qv = &$query->query_vars; if ( $pagenow == 'edit.php' && isset($qv['post_status']) && $qv['post_status'] == 'wc-priority-order' ) { $query->set('meta_key', '_priority_list'); $query->set('order_by', '_priority_list'); } return $query; } add_filter( 'pre_get_posts', 'filter_priority_orders' ); Thanks in advance!
I've solved my problem myself, thanks function filter_priority_orders($query) { global $pagenow; $qv = $query->query_vars; if ( $pagenow == 'edit.php' && isset($qv['post_status']) && $qv['post_status'] == 'wc-priority-order' && isset($qv['post_type']) && $qv['post_type'] == 'shop_order' ) { $query->set('meta_key', '_priority_list'); $query->set('orderby', 'meta_value_num'); $query->set('order', 'ASC' ); } return $query; } add_filter( 'pre_get_posts', 'filter_priority_orders' );
stackexchange-wordpress
{ "answer_score": 1, "question_score": 1, "tags": "woocommerce offtopic" }
Remove user profile field I'm looking for custom code to remove fields on user profile like you see in the pictures : ![remove what is in red color]( I would also like to replace Gravatar images with simple photos from the media library: ![remove what is in red color](
### Part 1 Create `wpse_admin_user.css` file and put it in your current theme, where `style.css` is: tr.user-admin-color-wrap, tr.user-admin-bar-front-wrap { display: none; } Add this code to your theme's functions.php: function wpse_user_admin_script() { wp_register_style( 'wpse_admin_user_css', get_stylesheet_directory_uri() . '/wpse_admin_user.css' ); wp_enqueue_style( 'wpse_admin_user_css' ); } add_action( 'admin_enqueue_scripts', 'wpse_user_admin_script' ); ### Part 2 Install and activate Custom User Profile Photo plugin. You will be able to use pictures from media library.
stackexchange-wordpress
{ "answer_score": 1, "question_score": 1, "tags": "users, profiles" }
Align divs in a basic WordPress site Trying to clean up a site where someone used a "page builder" plugin in addition to the existing theme. On the page below, I removed all plugin code, but... The text below "Next Steps" does not top align with the "Free" button to the right. I tried using the float method and even making the divs display as table cells. It would work in a temporary test environment but not once I pasted it into this site. Example page
Slowed down the pace of edits and thought it through ... working now! The padding-top compensates for a tendency of the button to sit too high. `.alignleft-luke5 { width:70%; height:200px; float: left; } .alignright-luke5 { width:30%; height:200px; float: left; padding-top:0.8em; } `
stackexchange-wordpress
{ "answer_score": 0, "question_score": 0, "tags": "css" }
Custom archive widget drop down menu need to display archive drop down as Jan-march 2017, April-June 2017 like that, is that possible
The archives widget uses the `wp_get_archives` function to generate the dropdown list. As you can see from the source code, there is no native way to use other dropdowns than yearly/monthly/weekly/daily. Unfortunately, there also is no hook to insert your own quarterly dropdown. So, there is no easy way to do this. There is a deeper problem, too: there is no native WP way to link to a bunch of posts by quarter as there is for years and months. This exists: `www.example.com\2017\05`. This doesn't: `www.example.com\2017\Q1`. That doesn't mean it can't be done. But you're looking at building your own archive dropdown widget and combining it with a smart date query to be able to link to a quarterly archive.
stackexchange-wordpress
{ "answer_score": 0, "question_score": 0, "tags": "widgets, archives" }
Output plugin post like system count I am working with WordPress Post Like System plugin for user likes on a post. I am wondering if there is a way to just output the post likes count without using the shortcode? Just showing the number of likes as text. I'm not sure how to approach this but any help would be much appreciated!
According to the plugin's readme file, you can call a PHP function in your theme to display the likes, but that includes the buttons. Looking into that function shows the like count is coming directly from post meta, so you can use the same query the plugin uses to get the count: $like_count = get_post_meta( $post_id, "_post_like_count", true ); In your theme where you want to print the count, you can use echo esc_html( $like_count );
stackexchange-wordpress
{ "answer_score": 2, "question_score": -1, "tags": "plugins, post meta" }
How to set a Cookie-Free Domain with WordPress? I recently set up a WordPress site here. I added these two lines in wp-config.php: define("COOKIE_DOMAIN", "www.artisanplombier-pascher.com"); define("WP_CONTENT_URL", " When I request the homepage and inspect the network queries with my browser, the assets are loaded with "static" subdomain, however a "cookie" header request is also sent along with the other parameters. I don't know what I am missing.
Your mistake is the WP_CONTENT_URL's postfix. You should set the definitions in the following manner: define("COOKIE_DOMAIN", "www.artisanplombier-pascher.com"); define("WP_CONTENT_URL", " Then, you should configure the _static._ subdomain's path in your server's configuration file or your hosting's control panel. Create a subdomain named "static" or something similar and configure its path to your (WordPress) website's "wp-content" folder. And finally, you need to check the following redirects: -> is path to -> and your "upload" folder (images folder for wp) is here; and it's root domain path is; Best Regards.
stackexchange-wordpress
{ "answer_score": 3, "question_score": 0, "tags": "cookies, optimization, deployment, installation" }
How to receive security update notification email? I would like to know WordPress security and release update via email? Where can I subscribe email notification?
For release updates, you can sign up at < If you'd like more regular updates on the development process, visit < and sign up there.
stackexchange-wordpress
{ "answer_score": 0, "question_score": 2, "tags": "admin, updates" }
WP RSS Aggregator plugins breaks after switch to HTTPS We use the WP RSS Aggregator plugin to gather feeds from various sources. Our site previously ran on HTTP. After switching to HTTPS, the plugin has stopped working. If I manually try to fetch the feeds, nothing happens. The WP RSS error log is empty. Does anyone have any ideas as to why this might happen? It seems like a minor change that wouldn't effect the plugin from curl'ing down feeds. UPDATE: It's definitely an issue with our reverse proxy setup, but I'm not sure how to address it yet. The problem is with WP-cron and our reverse proxy setup. The SSL is terminated at the nginx layer. Our backend Apache servers are only talking HTTP. So I get the following error from WP-Cron: There was a problem spawning a call to the WP-Cron system on your site. This means WP-Cron events on your site may not work. The problem was: cURL error 7: Failed to connect to www.example.org port 443: Connection refused
This sounds like your local DNS settings resolve your domain name to the server instead of going properly to the proxy. hmm, reading the question again, if the proxy is on the same machine, you might have some firewall misconfiguration. Best long term solution is just not to rely on the wordpress cron and replace its use with the OS cron < .
stackexchange-wordpress
{ "answer_score": 1, "question_score": 0, "tags": "plugins, rss" }
Translate site in own text-language I have content in two language for my website(English and Arabic) .I want to translate website in these my two custom content language rather then any language translator. Please tell me how can i translate my site in these two language only. I mean website is showing in English by default but when i choose Arabic language like any language translator, its showing my own Arabic language on my website. Please help me asap. Thank you in advance.
If you are looking for a translation plugin - I can recommend the two the Polylang and qTranslate X. The main difference is that the Polylang creates separate language version posts for a specific page, the qTranslate-X keeps all the language versions in the same post's fields using its specific markup. The Polylang is actively updated, qTranslate-X has its hard time lately so you can have problems implementing it with some latest more complicated plugins like for instance Yoast SEO. It depends what you like and what you need - check them both and see for yourself.
stackexchange-wordpress
{ "answer_score": 0, "question_score": 0, "tags": "customization, language, text" }
Can access main URL and Dashboard but not any posts or pages I'm not sure what happened. But this week I suddenly lost access to the pages and posts of this URL: www.michaelfstewart.com GoDaddy had notified me of some files to delete as they were suspicious. I did so, but pretty sure I still had access to those pages after that. Any ideas? Thank you!
Might be an issue with `permalink` or `htacces` file. try to reset permalinks to default and check.
stackexchange-wordpress
{ "answer_score": 0, "question_score": 0, "tags": "user access" }
How do you add custom metadata to WooCommerce orders? Specifically a second external order ID I am working on building a custom integration from WooCommerce to our internal ERP. I hooked into the `woocommerce_checkout_order_processed` so that when an order is placed I send all relevant information to our ERP and the reply is an order ID. This is a different order ID than what is in WooCommerce and I need a way to map the ERP order ID to the WooCommerce order. What is the best way to accomplish this? I have tried adding custom metadata, but so far that has failed. `add_metadata( "shop_order", $order->id, "mapics_order", (string) $orderNumber, TRUE );` and am trying to avoid using `wc_add_order_item_meta` since this is not item specific, but for the entire order itself.
you can use `woocommerce_checkout_update_order_meta` hook to update order meta. Please check sample code add_action('woocommerce_checkout_update_order_meta', 'custom_checkout_field_update_order_meta'); function custom_checkout_field_update_order_meta($order_id) { session_start(); if ($_SESSION['mapics_order']) update_post_meta($order_id, 'mapics_order', esc_attr(htmlspecialchars($_SESSION['mapics_order']))); }
stackexchange-wordpress
{ "answer_score": 3, "question_score": 1, "tags": "woocommerce offtopic" }
Wordpress Woocommerce product-category info on one line As the title says. I want to list info about different courses with info where each class have all the info, including the "Add to Cart" button, on one line. I've managed to change the SKU and Categories to time and place. I've found the CSS that styles (.berocket_lgv_additional_data) but can't get it to show all info on one line. I would think if I get the PHP that shows product name and product description mated in meta.php with old SKU and Categories it would show on one line? Also, that button on the left side is killing me.
Okay, if someone wants to know. I used the plugin Grid/List View for WooCommerce. Then added a div in the php script additional_product_data.php The div i called wrapper and included all the divs in that script. Then i gave the div id="wrapper" display=inline block in my templates style.css Also all the other "display" in the css doc of the plugin was given; inline block. Then i got all the info on one line.
stackexchange-wordpress
{ "answer_score": 0, "question_score": -1, "tags": "woocommerce offtopic" }
Get random terms Is it possible to get random terms? To get random posts you could use `WP_Query` and set `'orderby' => 'rand'`. But is there any way to do that with terms? I've tried this: $terms = get_terms( array( 'taxonomy' => 'webshops', 'hide_empty' => false, 'orderby' => 'rand', 'number' => 6 ) );
Unlike a normal `WP_Query()`, `get_terms()` or `WP_Term_Query()` does not have random ordering. You would either need to do it in SQL yourself or grab all the terms and shuffle them, pulling out 6 to make your random term array: // Get all terms $terms = get_terms( array( 'taxonomy' => 'webshops', 'hide_empty' => false, ) ); // Randomize Term Array shuffle( $terms ); // Grab Indices 0 - 5, 6 in total $random_terms = array_slice( $terms, 0, 6 );
stackexchange-wordpress
{ "answer_score": 10, "question_score": 1, "tags": "wp query, terms" }
How to write one comment and publish on every post using database or plugin? I have about `500 posts` published in WordPress now I want to add one same comment on every post. How to do the by the database. I search about it, but not a good luck. thanks in advance for the help.
It would be safer to use `[wp_insert_comment()][1]` rather than manually through MySQL. WP often inserts data in multiple tables - using its core functions helps ensure that all of the data gets added in all of the right tables. I'd suggest creating a query to pull all published posts. Then, set up a foreach loop that calls `wp_insert_comment()` on every post, thus inserting the comment on each one.
stackexchange-wordpress
{ "answer_score": 3, "question_score": 1, "tags": "plugins, php, database, mysql" }
Is there a way to conditionally check whether a WordPress post title is empty? Inside a WordPress loop, I'd like to conditionally check to see if the post has a title, in order to provide necessary wrapping HTML. If the post does not have a title, I don't want any of the wrapping HTML to appear.
While you're in The Loop you can check against the WP_Post Object like so: <?php while( have_posts() ) : the_post(); ?> <?php if( ! empty( $post->post_title ) ) : ?> <h1><?php the_title(); ?></h1> <?php endif; ?> <?php endwhile; ?>
stackexchange-wordpress
{ "answer_score": 3, "question_score": 0, "tags": "php, functions, theme development" }
Can I get all options using the option group id? I would like to return all the option that I registered under a specific group id. Is there a way to do this?
I don't think there is a function. But you can create your own like this function function_name(){ global $new_whitelist_options; // array of option names $option_names = $new_whitelist_options[ 'your_option_group_name' ]; // your_option_group_name is in register_setting( 'your_option_group_name', $option_name, $sanitize_callback ); foreach ($option_names as $option_name) { echo get_option($option_name).'<br>'; } } See: here **EDIT:** **$new_whitelist_options** was renamed to **$new_allowed_options** since 5.5.0. view change log here
stackexchange-wordpress
{ "answer_score": 3, "question_score": 3, "tags": "plugin development" }
Copy Tags from one post type to another post type I am using Ultimate member plugin and my client wants to copy all the tags from Ultimate Member plugin (custom post type) to WordPress standard Posts type tags. Is there any query that I can copy all these? Because there are hundreds of tags that I have to copy and manually it will take much time. So if I will be able to do this with the query then it will save a lot of my time.
You didn't post any code, including the name of custom post type that Ultimate Member is creating, but this is the general query for your request: function copy_my_tags(){ // Get every terms used by Ultimate Member $terms = get_terms( array( 'taxonomy' => 'custom_tax', 'hide_empty' => false, ) ); // Run a loop and create tags based on custom terms foreach ($terms as $term) { // Check if the tag already exists if(!term_exists($term , 'post_tag')){ wp_insert_term ( array( $term, 'post_tag', ); } } } add_action('init','copy_my_tags'); Add this code to your theme's functions.php file, and load any page. Once you load WordPress, the tags will be copied. Then you should delete this code to prevent it from running each time a page is loaded.
stackexchange-wordpress
{ "answer_score": 3, "question_score": 3, "tags": "plugin development, tags" }
How to get all taxonomies which can be added in menu? I am trying to get list of available taxonomies which WordPress admin users can use in menu section, like `Categories`, `Tags`, `Product Categories`, `Product Tags` or any custom taxonomy for custom post type. Using `get_taxonomies` results all taxonomies, some of which are not available in Menu screen, for example Product shipping Class (from woocommerce). In short, I am trying to get all those taxonomies which are used with `Post`, `Page`, `Products` or any other `Custom Post Type` in right side of editing screen.
The taxonomies visible in the admin menu are exactly those taxonomies that were registered with `show_in_menu = true` and `show_ui = true`. For a reference on this, see the documentation on `register_taxonomy`, the function for adding (custom) taxonomies. To query these taxonomies, use the corresponding parameters in `get_taxonomies`: get_taxonomies( array( 'show_ui' => true, 'show_in_menu' => true, ) );
stackexchange-wordpress
{ "answer_score": 0, "question_score": 1, "tags": "custom taxonomy, menus, taxonomy" }
Button insert link on front wp_editor not working I display a wp_editor on the front-end and everything was going fine until a recent WP update. Now, the "insert/edit link" is not working due to a Javascript error: Uncaught TypeError: Cannot set property 'tempHide' of undefined This error only appears on front-end. The back-end is going fine. I've looked for it on StackExchange and Google. Maybe I'm not using the right keywords, but I don't find anyone with the same problem... Has anyone an idea?
I found it at last! Using the browser debugger, I found that there was a "editor.wp" which was undefined (in the complete version of the js file). Then I understood that the "wordpress" plugin was not used in the editor. When calling the function wp_editor, I was setting a list of plugin : paste, wplink, textcolor. It was working until a specific WordPress update. I just had to add the "wordpress" plugin in the list, and now it's working.
stackexchange-wordpress
{ "answer_score": 1, "question_score": 1, "tags": "javascript, links, front end, wp editor" }
Do shortcodes in title before permalink is generated I need a special behavior in the title, so I use shortcodes there, the display is fine (I just use filters `the_title`&`single_post_title`), however when permalink is generated, the shortcode stays there (it just strips out the `[` `]` )... I need to somehow change the source title **before** the link is generated, since **_I don't want to do/recreate the permalink logic again_**. Note: When I used HTML directly instead of shortcodes, the desired result is delivered :) (HTML is stripped, but its inner contents are kept). However, that is unacceptable for a regular user case.
Lately I've found out that, the link is generated through `get_sample_permalink()` which uses `sanitize_title()` ... and there is a filter "`sanitize_title`" - provided with a lots of useful info :) add_filter( 'sanitize_title', function( $title, $raw_title, $context ){ $title = do_shortcode($title); return $title; //filter => must return! }, 1, 3 ); //top priority (1), 3 arguments accepted From what is seems to me `sanitize_title()` basically prepares title for an ID generation - removes html, php, and accents. **Note:** `$title` provided to filter has already gone through process of removing accents - if you want the original - just use `$raw_title` as source ;)
stackexchange-wordpress
{ "answer_score": 0, "question_score": 0, "tags": "permalinks, shortcode, title" }
How to generate a hierarchical list of all pages and child-pages using a regular query? I'm trying to query all the pages (just the title) to generate a ul/li-tree structure, using a regular query: // The Query $query = new WP_Query( $args ); // The Loop if ( $query->have_posts() ) { while ( $query->have_posts() ) { $query->the_post(); ?> <li><?php the_title(); ?></li> <?php } } else { // no posts found } Is it possible to detect the level of the current page/post, and whether it has a parent or not? I just want it to output something like this: <ul> <li>Parent 1<ul> <li>Child 1-1</li> <li>Child 1-2</li> </ul></li> <li>Parent 2</li> <li>Parent 3</li> </ul>
You can use `wp_list_pages()` instead. Just pass your post type in if you're trying to list something other than Page-pages: <ul> <?php wp_list_pages(array( 'post_type' => 'yourposttype', 'title_li' => '' ) ); ?> </ul> If you wanted to display this on all post types you could use <ul> <?php wp_list_pages(array( 'post_type' => $post->post_type, 'title_li' => '' ) ); ?> </ul> which would automatically grab the post type of the currently viewed item and display the full tree for that post type.
stackexchange-wordpress
{ "answer_score": 1, "question_score": 0, "tags": "theme development" }
stylesheet in header or functions? So I have an interesting dilemma here. My understanding is that best practice is to load up stylesheet, including Bootstrap css and javascript via functions.php file. However, in the header.php file the stylesheet snippet has this: <link rel="stylesheet" href="<?php bloginfo('stylesheet_url'); ?>" type="text/css" media="screen" /> The "this" that I refer to is the media="screen". If I am not mistaken this is part of the @media rules, but I am not sure if it will be necessary for refactoring this site into a bootstrap mobile responsive site. Otherwise, I would just eliminate it and place this piece of code: wp_enqueue_style('stylecss', get_stylesheet_uri()); into the functions.php file. My question being, am I going to mess things up for me down the line when I implement bootstrap templates by eliminating the line of code in the header for the sake of WP best coding practice?
`wp_enqueue_style` has a 5th parameter that represents the `media` attribute. < You could do the following to load this correctly: `wp_enqueue_style( 'stylecss', get_stylesheet_uri(), array(), false, 'screen' );` Hope it helps!
stackexchange-wordpress
{ "answer_score": 3, "question_score": 0, "tags": "wp enqueue style, css" }
How to override the email function by using filters? Is there a `do_action()` or an `add_filter()` that I can implement to use my own send mail function instead of Elegant Theme's `wp_mail()` function in their Divi theme? I want to intercept the Divi emailer function and use my own for a contact us form.
If Divi theme uses `wp_mail()` function (which most likely does), you can use the `wp_mail` filter to pass your own arguments to the function: function filter_divi_mail( $args ) { // Modify the options here $custom_mail = array( 'to' => $args['to'], 'subject' => $args['subject'], 'message' => $args['message'], 'headers' => $args['headers'], 'attachments' => $args['attachments'], ); // Return the value to the original function to send the email return $custom_mail; } add_filter( 'wp_mail', 'filter_divi_mail' );
stackexchange-wordpress
{ "answer_score": 2, "question_score": 3, "tags": "filters, wp mail" }
I'm trying to display product categories on each product in the list To be more precise I'm trying to get the category name as a class. I want it under the title, so something like: echo '<h3><a href="' . get_the_permalink() . '">' . get_the_title() . '</a> </h3>'; echo '<span style="display:none;" class="prodcat'; $categories = array( Category1, Category2); foreach ($categories as $category) { echo ' ' . $category . ''; }; echo '"> </span>'; I just can't figure out how to get he categories from the product to replace "array( Category1, Category2);" I've messed around a whole lot, the closest I've gotten is displaying "Array"
Product categories in Woocommerce is a term, so you can get the categories with get_the_terms function: echo '<h3><a href="' . get_the_permalink() . '">' . get_the_title() . '</a></h3>'; echo '<span style="display:none;" class="prodcat'; $categories = get_the_terms( get_the_ID(), 'product_cat' ); foreach ($categories as $category) { echo ' ' . $category->name . ''; }; echo '"> </span>';
stackexchange-wordpress
{ "answer_score": 0, "question_score": 0, "tags": "woocommerce offtopic, categories" }
Display only past events on that page using Visual Composer Grid Bulider I am using visual composer in WordPress,In the i have create the custom post type for the event and displaying the events such as upcoming event and past event using grid builder.the upcoming event is displaying fine but the past event is showing all post,I need to display only the past events i have try some methods in that i have write the custom query for the past event to comparing with current date. **Custom field name:** > date_short_order **Custom query:** post_type=event&posts_per_page=3&post_status=publish&meta_key=date_short_order&orderby=meta_value_num&order=DESC&meta_query%5B0%5D%5Bkey%5D=date_short_order&meta_query%5B0%5D%5Bvalue%5D=$today&meta_query%5B0%5D%5Bcompare%5D=<&meta_query%5B0%5D%5Btype%5D=DATE I am struggling past one week with this any one help me.
Finally i got answer. post_type=event&meta_query%5B0%5D%5Bkey%5D=date_short_order&‌​meta_query%5B0%5D%5B‌​value%5D=$today&‌​meta_query%5B0%5D%5B‌​compare%5D=%3C&meta_‌​query%5B0%5D%5Btype%‌​5D=DATE post_type=event&meta_query%5B0%5D%5Bkey%5D=date_short_order&‌​meta_query%5B0%5D%5B‌​value%5D=$today&‌​meta_query%5B0%5D%5B‌​compare%5D=%3C&meta_‌​query%5B0%5D%5Btype%‌​5D=DATE
stackexchange-wordpress
{ "answer_score": 1, "question_score": 1, "tags": "custom field, query" }
change page name on page list I'm looking for the way to changes terms on wordpress backoffice. exemple : pages name on list page. ![enter image description here]( I don't found the .PO or .MO on wp-content/language/ to make changes. Do you have an idea?
You can change built in post type labels with the `post_type_labels_{$post_type}` filter: function wpd_change_page_labels( $labels ) { $labels->menu_name = 'Specials'; $labels->name = 'Specials'; $labels->singular_name = 'Special'; return $labels; } add_filter( 'post_type_labels_page', 'wpd_change_page_labels' ); EDIT- Refer to `register_post_type` for a full list of labels, there are probably some others you'll want to add to this.
stackexchange-wordpress
{ "answer_score": 1, "question_score": -2, "tags": "posts, pages, translation" }
Human Time Diff, change mins to minutes On my WordPress site, I am using the human time difference for the post date. If you have a post that was posted `59 minutes ago` or under it appears as posted `1 min ago`, `5 mins ago`, or posted `35 mins ago`. Is there a way that I can change mins to minutes? This is the code I have. <div class="front-page-date"> <?php echo human_time_diff( get_the_time('U'), current_time('timestamp') ) . ' ago'; ?> </div>
You can do: echo str_replace('mins', 'minutes', human_time_diff( get_the_time('U'), current_time('timestamp') ) . ' ago'); **Update:** The same using filter as suggested: add_filter('human_time_diff', 'new_human_time_diff', 10, 2); function new_human_time_diff($from, $to) { // remove filter to prevent the loop remove_filter('human_time_diff', 'new_human_time_diff'); $timediff = str_replace('mins', 'minutes', human_time_diff($from, $to) . ' ago'); // restore the filter add_filter( 'human_time_diff', 'new_human_time_diff', 10, 2); return $timediff; } echo human_time_diff(get_the_time('U'), current_time('timestamp'));
stackexchange-wordpress
{ "answer_score": 3, "question_score": 0, "tags": "posts, functions, post meta, date, timestamp" }
Is it possible to keep the page title from actually appearing at the top of the page? I want the pages named and not left blank for organizational purposes, but can I keep the titles from actually showing up on the page? I've looked everywhere.
Displaying the title is part of the code inside your theme. But you can remove (hide) the title from display by looking at the CSS 'class' or 'id' your theme assigns to the title. You do this with developer tools like Firebug. Assume that the text of the title specifies the class of 'thetitle'. Add this CSS to your theme (via the additional CSS that the theme may allow): .thetitle {display:none; } If your theme does not allow 'additional CSS', then your best bet is to create a Child Theme for your theme, and add the above CSS to the `style.css` of your child theme. (You don't want to modify your theme's `style.css` file, as any changes you make would be overwritten with a theme update.) Another option is to install a plugin that allows you to add additional CSS, if your theme does not support that. There are several that are available.
stackexchange-wordpress
{ "answer_score": 0, "question_score": -1, "tags": "pages, title" }
Copyright symbol not working I can't get the &copy element to work to display the copyright symbol on my website. It just shows it as plain text. Anybody know a workaround for this?
Are you using `&copy;` (with a trailing semicolon)?
stackexchange-wordpress
{ "answer_score": 1, "question_score": -2, "tags": "html, copyright" }
jQuery not available to other scripts I'm getting console errors that "jQuery is not a function" even though: a) it IS being enqueued correctly and called in the header b) it IS listed as a dependency for the scripts that are enqueued. I've reverted to older versions of WordPress (now back to 4.8), I've disabled and enabled plugins as well with none of that working. I don't understand how jQuery is called correctly on the page but other scripts aren't able to use it as a function? Site is < for reference
You've got two copies of some inline script var $mcj = jQuery.noConflict(true); inside a commented section 'mc_embed_signup'. The 'true' here is `removeAll`: > removeAll > Type: Boolean > A Boolean indicating whether to remove all jQuery variables from the global scope (including jQuery itself). You should track down this script and try and understand what it's trying to do, or just remove the 'true' if you're sure you don't need it.
stackexchange-wordpress
{ "answer_score": 1, "question_score": 1, "tags": "theme development, jquery, javascript, wp enqueue script" }
Keep br tags from stripping Is there some filter to disable this, sometimes awful feature? I need content of some custom post type to be displayed intact, with all of `<br>`s. To get the content I'm using `get_the_content();` inside of `WP_Query` loop, inside of shortcode function. I'm grateful with any clue, but answer without the word "plugin" would blow my mind.
Since any attribute added to `<br>` tag, including class names and `data-attr`s keeps them from stripping, quick and incomplete way could be: function filter_function_name( $content, $post_id ) { $content = str_replace('<br>', '<br data-x>', $content); $content = str_replace('<br >', '<br data-x>', $content); $content = str_replace('<br />', '<br data-x>', $content); $content = str_replace('<br/>', '<br data-x>', $content); return $content; } add_filter( 'content_edit_pre', 'filter_function_name', 10, 2 );
stackexchange-wordpress
{ "answer_score": 0, "question_score": 0, "tags": "custom post types, filters, actions, wp autop" }
Changer numbers of columns in woocommerce shop I have a problem with my shop columns in WooCommerce. I would like to display 4 columns in my shop but unfortunately there is just 3 columns. I use the Storefront theme for my shop, so I have looked the `storefront-template-fonction.php` file and the different `apply_filters` are setting up on 'columns'=>4. Exemple: $args = apply_filters( ‘storefront_popular_products_args’, array( ‘limit’ => 4, ‘columns’ => 4, ‘title’ => __( ‘Fan Favorites’, ‘storefront’ ), ) ); The only "solution" I have found is to used the shortcode `[recent_products per_page="12" columns="4"]`. But with that, I have another problem, I have the 4 columns that I wanted with my products but the 3 previous columns displayed below too. I work in Local with an Uwamp server and the last update of WordPress, Storefront and WooCommerce. I hope there is somebody who can help me.
Use this in `functions.php` file. It is better to create site specific plugins. add_filter( 'storefront_loop_columns', 'sf_columns_per_row' ); function sf_columns_per_row() { return 4; }
stackexchange-wordpress
{ "answer_score": 1, "question_score": 0, "tags": "customization, woocommerce offtopic, columns" }
Problem when try to add ++1 for user meta This is my code: $user_user_count = get_user_meta( "_user_count", $user_id ); $user_user_count = ( isset( $user_user_count ) && is_numeric( $user_user_count ) ) ? $user_user_count : 0; update_user_meta( $user_id, "_user_count", ++$user_user_count ); When I do the action, it adds the meta successfully with 1. The issue when trying to do the action again is that: it's not changed to 2, it's still 1.
The problem here is twofold: * the `++` operator is applied on an array. * the user id and the meta key need to be swapped in `get_user_meta()` So use `get_user_meta( $user_id, "_user_count", true );` to get user meta. Note that the third input parameter is _false_ by default and an array is returned. Setting it to _true_ , returns a single value instead.
stackexchange-wordpress
{ "answer_score": 3, "question_score": 0, "tags": "query, user meta" }
Posts and Pages: 404 Page not found Every post and page is not found. I checked .htaccess, generated a new one, debugged (disabling plugins), checked the static page and the blog page, also nothig. The last thing I did was check if everything was ok in the database, and the posts and links are there and if I use the database url is the same 404 not found.
Did you try to re-save Permalinks? Navigate to: WordPress Dashboard > Settings > Permalinks: Click "Save Changes" and then click on the link of the page that should work from the "Edit Page" of that page. Also review Permalinks settings if they are correct. If it still doesn't work, you can try to debug the generated permalinks with Debug This plugin. After activating this plugin go to: Admin Bar > Debug This > Query > Rewrites and check if the rewrite rules are correct and exist for the url that should work.
stackexchange-wordpress
{ "answer_score": 1, "question_score": 0, "tags": "posts, pages, 404 error" }
Change Sidebar for rewritten page I have a number of rewrite rules set which output content correctly however I want to extend this so that the sidebars that appear on that rewritten page can also be amended so that a sidebar is called depending on the `query_vars` used. Is there anyway to manipulate what is rendered with `dynamic_sidebar` so we can query the `query_vars` and choose an appropriate sidebar to display? Or is it a case of wrapping `dynamic_sidebar` with tests to call the correct sidebar?
It's hard to tell your exact requirements, but testing to see which handle to pass to `dynamic_sidebar` is probably your best bet, since it'll allow you to administer each version from the WordPress back-end. Don't forget to register each version with `register_sidebar` The other thing that might be what you're after is the `sidebars_widgets` filter, which lets you edit the global widgets array when it's accessed within `dynamic_sidebar`. A sidebar is part of the template applied to the post/page, I can't see any way that changing it directly via a rewrite rule would make sense from a functional perspective.
stackexchange-wordpress
{ "answer_score": 0, "question_score": 0, "tags": "sidebar, rewrite rules" }
URLs fine in database but wrong in output I have my URLs all right in the database (at least, "Better Search & Replace" doesn´t find the faulty ones, neither does phpMyAdmin), but in the frontend they are messed up. Basically http:// is missing the : so images won´t load correctly, links are wrong etc. pp. Home and Website URL are fine in the backend and _some_ images and links are working. I already deleted and rebuilt the .htaccess, so it´s not about that either, I think. What might cause this behaviour? Strangely configured server of the client? **Update 1:** I tried disabling all plugins and switching to a standard theme. This didn´t change anything.
Ok, this was pretty strange. While only `http//` showed up in the URLs the database fields for the corrupted URLs were ` which obviously resulted in the error. I did another search & replace for those "double http" and that fixed it in the end. Still no idea why this only happened to some URLs but I´m happy I figured it out. So having a second look, two days later, sometimes is a valid solution. :-)
stackexchange-wordpress
{ "answer_score": 0, "question_score": 0, "tags": "urls, server" }
Store regex expression in Wordpress DB using Options API I have been searching all afternoon for a solution and couldn't find one. I am writing a plugin which needs to store regex expressions in the WP DB. An example expression is the following. /(http:\/\/)(.*?)(example.com)/i Storing the expression seems to work fine with `update_option()` and the entry in the database has the backslashes escaped with another backslash. However, when retrieving the option using `get_option()` the escape backslashes aren't removed, and I need to apply `stripslashes()` to get rid of them. Is this a reliable method to manage the storage and retrieval of backslashes in the WP DB? Are they missing a `stripslashes()` or similar when the `get_option()` is used to retrieve the expression from the database?
Wordpress by default "escapes" all slashes and quotes in all input (historical reason, relic of the time PHP could have been configured to do it by default, or not). If you are handling forms by yourself instead of using the APIs you will need to strip the slashes, probably best to be done when saving the data.
stackexchange-wordpress
{ "answer_score": 0, "question_score": 1, "tags": "api, options, regex" }
Set Default Page On Customizer Live Preview I have wordpress site and set login page as static front page. If I go to theme customizer exactly it will use front page to show site live preview. How to change page live preview to another page? In this case I will use post page as live preview page in customizer.
The default URL being previewed is `home_url( '/' )`. When no `url` query parameter is present when opening `customize.php`, this is the preview URL that is used. You can override the previewed URL when there is no `url` query parameter to supply a different default using something like this: add_action( 'customize_controls_init', function() { global $wp_customize; if ( ! isset( $_GET['url'] ) ) { $wp_customize->set_preview_url( get_permalink( 1 ) ); } } );
stackexchange-wordpress
{ "answer_score": 5, "question_score": 2, "tags": "theme customizer, frontpage" }
In WooCommerce filter the available Payment Methods by User Role Is it possible to filter available payment methods to certain user roles just using the WooCommerce configuration? Without adding anything to any template file I mean. What I want to achieve is to give the possibility to pay with credit card only to certain users.
It is not possible by WooCommerce default configuration. You have to install below plugin. < or programmatically, you can refer below link. <
stackexchange-wordpress
{ "answer_score": 8, "question_score": 2, "tags": "woocommerce offtopic, user roles" }
What is the point of using the front-page.php template? You can use **front-page.php** to create a static front page, it will override all other templates and static front page settings, but the problem is that you can't edit the front page then. You can't edit the front page from inside WordPress, and add content to it, like you can with pages. If I choose to create a new page and use it as the static front page from the reading options in WordPress, I am able to edit this page. ![enter image description here]( The point of a CMS system is to make it easy to manipulate content, using **front-page.php** I have to edit the code directly. So why should I use **front-page.php** instead of adding a page and setting it to be the static front page in reading options?
You would use the `front-page.php` template because it allows to have custom content and layout for your website's static front page. You can edit content on your static front page from inside the WordPress admin if the `front-page.php` template contains the `the_content()` template tag or similar. It really depends on what your content and presentation requirements are for your static homepage. Leaving out the `front-page.php` might be enough if you have basic content and presentation requirements. If your content and presentation requirements are more complex you might need to code or find a theme with a `front-page.php` template that better suits your needs.
stackexchange-wordpress
{ "answer_score": 0, "question_score": 0, "tags": "theme development, themes, templates, page template" }
Admin page button create new I have made a plugin and now i want to include a button into my plugin, see image. How can i achieve that? ![enter image description here](
Its just HTML code. Follow this structure. <div class="wrap"> <h1> PAGE TITLE GOES HERE <a href="" class="page-title-action"> BUTTON TEXT GOES HERE </a> </h1>
stackexchange-wordpress
{ "answer_score": 1, "question_score": 0, "tags": "plugins" }
Update post terms with custom taxonomy I have multiple customs post types: > CPT1 = "bike", > > CPT2 = "car" They share a common custom taxonomy _"colors"_ (with terms : _"blue"_ , _"red"_ ). They also have their own taxonomy with terms like : _"blue_bike"_ , _"red_bike"_ .. I'm searching how to auto update the post taxonomy with the custom taxonomy. For example : If i only select the custom taxonomy term _"blue"_ in the Custom Post Type "Bike". Is it possible when i save the post, it will automatically update the post with the term _"blue_bike"_ ? And if it's possible how to do that ? I'm trying for the past couple hours with the function `wp_set_object_terms`, with no result (my php skills are not so good)
Yes it is. But you have to know the exact taxonomy's slug, since colors are not like preserved terms to be generated programmatically. Here is an example of how to do it: // run our function when a post is published add_action('save_post','update_my_taxonomies'); function update_my_taxonomies($post_id){ // Check if the post has a particular taxonomy if(has_term( 'blue', 'colors', $post_id )){ // Assign a term to our post wp_set_object_terms( $post_id, 'blue', 'blue_bike' ); } } This will set the `blue` for the `blue_bike` if the post has the `blue` term as its `color` taxonomy.
stackexchange-wordpress
{ "answer_score": 1, "question_score": 2, "tags": "custom post types, custom taxonomy, terms" }
Kirki: generate toggles for each taxonomy term I'm using Kirki and trying to generate a toggle for each term in custom taxonomy (to add ability to show/hide posts for each term in the theme later): function generate_toggles() { $months = get_terms( array('months') ); foreach ($months as $month) : Kirki::add_field( 'mytheme', array( 'type' => 'toggle', 'settings' => $month->slug, 'label' => __( 'Июль', 'my_textdomain' ), 'section' => 'months', 'default' => '1', 'priority' => 10, )); endforeach; } add_action('???', 'generate_toggles', 9999); What I don't understand though is where do I attach the action? Since I want it in Kirki panel – which action should I attach it to?
You can use a Kirki helper class for this (pass your taxonomy into **Kirki_Helper::get_terms** ), but you need to register after the taxonomies are registered, otherwise you get an error: function my_theme_add_categories_customizer_control() { Kirki::add_field('my_config', array( 'type' => 'multicheck', 'settings' => 'show_months', 'label' => esc_attr__('My Control', 'my_textdomain'), 'section' => 'months', 'priority' => 10, 'choices' => Kirki_Helper::get_terms(array('months')) )); } add_action( 'init', 'my_theme_add_categories_customizer_control', 12 );
stackexchange-wordpress
{ "answer_score": 1, "question_score": 0, "tags": "theme customizer" }
Why can't I include echo inside a variable? So for example, say I have a piece of text from a field I want to call. So I set the variables like this: <?php $text = get_field('text_field'); $outputtext = echo $text; ?> <p><?php $outputtext ?> </p> Is that not possible, and if so, why? Is there a particular reason why PHP is set up that way or something?
Not a WordPress question, but to do what you want you'd need to use an anonymous function. For your example, it's totally not needed or recommended, though. Echo shortcut syntax (e.g. `<?= $text ?>`) might interest you.
stackexchange-wordpress
{ "answer_score": 0, "question_score": -1, "tags": "php, functions" }
upload_max_size doesn't change I need to increase the max size for media. I've change my php.ini. I've change my .htaccess I've change my functions.php And it's not working. I've directly change (for try & test) the wp-include/media.php file like this : function wp_max_upload_size() { @ini_set( 'upload_max_size' , '64M' ); @ini_set( 'post_max_size', '64M'); $u_bytes = wp_convert_hr_to_bytes( ini_get( 'upload_max_filesize' ) ); $p_bytes = wp_convert_hr_to_bytes( ini_get( 'post_max_size' ) ); if(isset($_GET['mathieu'])) { var_dump($u_bytes); var_dump($p_bytes); } return apply_filters( 'upload_size_limit', min( $u_bytes, $p_bytes ), $u_bytes, $p_bytes ); } In the backoffice, I see : ![enter image description here]( I've no idea ...
I've find the problem. It's multisite WP. The settings need to be set in the multisite admin panel. <
stackexchange-wordpress
{ "answer_score": 1, "question_score": 0, "tags": "uploads, media" }
How to set custom avatar for users? I need to update custom image for users avatar on the time of registrations. I've using `Pie-register` plugin and it will allow upload profile picture but saving image `url` in `user_meta` and when try to get using get_avatar it returning default avatar, but I need upload image as user avatar on all places. Like user profile page , in comment section etc. Is this possible to display `user meta value` (image url) as user avatar for all users? Any help will be appreciated.
We can use the `get_avatar_url` filter to modify the avatar's url. If all the relevant `get_avatar()` calls, have _user id_ as an input argument, then it's easy to get the corresponding user's meta value, with `get_user_meta()`, within the filter's callback. Otherwise we need to handle all possible input cases, for `get_avatar( $some_input )`, as it supports: * user id, * user email, * gravatar md5 hash, * `WP_User` object, * `WP_Post` object * `WP_Comment` object. We can look into the `get_avatar_data()` function, to get an idea how to write such checks. An alternative, to determine the user id from the `get_avatar()` input, we might try to fetch the md5 hash from the generated gravatar url and use it to determine the user id from it. Maybe store the md5 email hash for each user. The `found_avatar` argument might also help, as it's true if the avatar was found for the given user. Hope it helps!
stackexchange-wordpress
{ "answer_score": 2, "question_score": 0, "tags": "users, user registration, avatar" }
Load admin bar without wp_head or wp_footer Is there any possible way to load admin bar without wp_head or wp_footer? If no, so maybe there is a way to load wp_head() or wp_footer() to catch only admin bar functions, styles and scripts? Is this even possible in worpdress? For example: `wp_head(load_admin_bar());` or something like that. Thanks for any answers.
Looks like, the only solutions which worked was to call admin bar directly. if (current_user_can('administrator') || current_user_can('editor')) { wp_admin_bar_render(); }
stackexchange-wordpress
{ "answer_score": 0, "question_score": 0, "tags": "php, functions, wp head, admin bar" }
Display child page content of a specific parent on home page This has been bugging the hell out of me, it should be so simple! I have a list of child pages under the parent called 'Our Homes'. The sitemap structure is as follows: * Home * Our Homes * home 1 * home 2 * home 3 For each home I want to display the following: * Title * Content snippet * Image * Map * Link to the child page for that home How do I loop through each child page under 'Our Homes' and display the specified content above from each on the home page?
To me, this sounds like a good use-case for a custom post type for homes, but, in any case, this is the basic concept you'd need to follow to get this working as you've got it set up now. <?php // Set up the objects needed $homes_wp_query = new WP_Query(); $all_wp_pages = $homes_wp_query->query(array('post_type' => 'page', 'posts_per_page' => '-1')); // Get the page as an Object $our_homes = get_page_by_title('Our Homes'); // Filter through all pages and find Our Homes' children $home_children = get_page_children( $our_homes->ID, $all_wp_pages ); // echo what we get back from WP to the browser echo '<pre>' . print_r( $home_children, true ) . '</pre>'; ?> That will print the post objects, then you can pick and choose which elements (like title, etc.) that you want to echo out
stackexchange-wordpress
{ "answer_score": 1, "question_score": 0, "tags": "php, loop, pages, child pages" }
How to get comment meta values by post ID I can get comment meta value by a comment ID. But if I want to retrieve a comment meta value of a single post's comments, how should I go?
The function `get_comments` allows you to select comments based on meta value. So, supposing you are on a single post page, so the current post is known, you would do this: $comments = get_comments (array ('meta_key'=> 'your_meta_key')); This will give you all comments with that specific meta key. You can even select them for a specific meta value, like this: $comments = get_comments (array ('meta_key'=> 'your_meta_key', 'meta_value'=> 'your_meta_value')); For instance, if you have a meta key called 'rating' and you want all comments that give the rating '5', you would do: $comments = get_comments (array ('meta_key'=> 'rating', 'meta_value'=> '5')); Beware that `$comments` returns as an array of comment objects, so printing goes like this: foreach($comments as $comment) { echo ($comment->comment_content); echo get_comment_meta($comment->comment_ID, 'rating', true) }
stackexchange-wordpress
{ "answer_score": 3, "question_score": 1, "tags": "theme development, comments" }
Remove parentheses from tag cloud count I am trying to remove the parentheses from the tag cloud widget and add in `<span class="post_count"> </span>` in place of it. Currently I have not been having any luck. I have this working for categories just fine but not sure why it won't work for the tag cloud count. function categories_postcount_filter ($variable) { $variable = str_replace('(', '<span class="post_count"> ', $variable); $variable = str_replace(')', ' </span>', $variable); return $variable; } add_filter('wp_list_categories','categories_postcount_filter'); Any help would be much appreciated! Thanks so much! Ponte
this is an example output of an tag cloud widget element (wp4.8): <a href=" class="tag-cloud-link tag-link-327 tag-link-position-22" style="font-size: 8pt;" aria-label="handcrafted (2 items)">handcrafted<span class="tag-link-count"> (2)</span></a> as you can see, the widget outputs some aria lable also using parentheses, which interferes with a simple string replace. the tag number including the parentheses is also already wrapped in a span. for example, try to use: function tagcloud_postcount_filter ($variable) { $variable = str_replace('<span class="tag-link-count"> (', ' <span class="post_count"> ', $variable); $variable = str_replace(')</span>', '</span>', $variable); return $variable; } add_filter('wp_tag_cloud','tagcloud_postcount_filter');
stackexchange-wordpress
{ "answer_score": 0, "question_score": 0, "tags": "tags" }
Clone the "proceed to cart" button and place it above checkout on the cart page, but only appear display size is 320px I have cloned the "proceed to cart" button and float on the upper-right corner on the Woocommerce cart page. However I want this button to appear only when the browser is compressed (simulating mobile display), but go away when browser is stretched to the size of PC display. How to do it? Here is the code I came up, but its not working. if(width <= 320){ add_action( 'woocommerce_before_cart', 'move_proceed_button' ); function move_proceed_button( $checkout ) { echo '<a href="' . esc_url( WC()->cart->get_checkout_url() ) . '" class="checkout-button button alt wc-forward" >' . __( 'Proceed to Checkout', 'woocommerce' ) . '</a>'; } } else if(width > 325){ remove_action( 'woocommerce_before_cart', 'move_proceed_button' ); }); ?>
I finally found solution to the above issue. At your wordpress functions.php inside your child-theme folder, add this code: add_action( 'woocommerce_before_cart', 'move_proceed_button' ); function move_proceed_button( $checkout ) { echo '<div class="mobile-checkout-btn text-right"><a href="' . esc_url( WC()->cart->get_checkout_url() ) . '" class="checkout-button button alt wc-forward" >' . __( 'Proceed to Checkout', 'woocommerce' ) . '</a></div>'; } The above code will clone the "Proceed to Checkout" button and place it above checkout. Now to make it appear only when screen size is that of a mobile device. Add this css codes on your style.css inside your child-theme folder. .mobile-checkout-btn { display: none; margin-bottom: 10px; } @media(max-width: 991px) { .mobile-checkout-btn { display: block !important; } } Hope this helps someone in the future.
stackexchange-wordpress
{ "answer_score": 0, "question_score": 0, "tags": "php, css, woocommerce offtopic, hooks" }
Show a list of user posts in the user admin page I have a Wordpress site with multiple authors. When i see a user profile page i want to have a list (maybe links) of the posts this user is the author of. How can i do it? I thought maybe running a standard Wordpress loop with author query but i don't know how to inject that php code in the user admin panel and i don't know if it will work and if that's the right approach...
You can use edit_user_profile (when viewing other user profiles) and show_user_profile (when viewing your own profile) actions to add information on profile page. So to have there the list of posts of the selected user you could add to your functions.php: function show_user_posts_on_profile( $user ) { $args = array( 'author' => $user->ID ); $user_posts = get_posts( $args ); ?> <h2>User Posts</h2> <ul> <?php foreach($user_posts as $user_post): ?> <li><a href="<?php echo get_permalink($user_post->ID); ?>"><?php echo $user_post->post_title; ?></a></li> <?php endforeach; ?> </ul> <?php } add_action( 'show_user_profile', 'show_user_posts_on_profile' ); add_action( 'edit_user_profile', 'show_user_posts_on_profile' );
stackexchange-wordpress
{ "answer_score": 0, "question_score": 0, "tags": "loop, admin, users, profiles" }
get the correct url for an folder in wp-includes wordpress I have added a folder (json) to `wp-includes` with a file inside called `users.json`. I am trying to write to this file but am getting the following error: > failed to open stream: HTTP wrapper does not support writeable connections I have been referencing it like the following in my php: `$file = " I believe I need to reference as per the name on the server. Is there a built in way to get this in wordpress? Something like `<?php echo get_template_directory_uri(); ?>`
You sad you put the json in `wp-includes`, but in the url you wrote `wp-content`. So I give you the code for getting the server path for both folders: // wp-includes $file = ABSPATH . WPINC . '/json/users.json'; // wp-content $file = WP_CONTENT_DIR . '/json/users.json'; You can find many WordPress constants (like `ABSPATH`, `WPINC`and `WP_CONTENT_DIR` on <
stackexchange-wordpress
{ "answer_score": 3, "question_score": 0, "tags": "php" }
footer display problem My footer is wide in my worspress page. But in one page it is not wide. How can i fix this problem. I use Simple Job Board plugin. This is the page with problem. < This is the page without problem <
* There is the two way to resolved this problem. 1 ) **using css** \- Add below css code in your theme style.css file. .single.single-jobpost .site-content.container {padding-bottom: 0;padding-left: 0;padding-right: 0;width: 100%;} 2 ) Please refer snapshot. \- <
stackexchange-wordpress
{ "answer_score": 0, "question_score": 0, "tags": "footer" }
Difference between 'type' => 'text' and WP_Customize_Control Heyo, I was wondering if there is any difference between the `'type' => 'text'` option in the `$wp_customize->add_control` control $wp_customize->add_control( 'textfield_1_control', array( 'label' => __('Textfield 1', 'cvh'), 'section' => 'test_section', 'settings' => 'textfield_setting_1', 'type' => 'text', 'description' => 'type => text', )); and the `new WP_Customize_Control` control. $wp_customize->add_control( new WP_Customize_Control( $wp_customize, 'textfield_2_control', array( 'label' => __('Textfield 2', 'cvh'), 'section' => 'test_section', 'settings' => 'textfield_setting_2', 'description' => 'WP_Customize_Control', ))); The output is the exact same (textfield). ![enter image description here](
There isn't really much of a difference for the default controls. Using the Class is needed for using custom built controls. So basically your first example is the short form of the second one only available for core controls. For details have a look at the documentation.
stackexchange-wordpress
{ "answer_score": 2, "question_score": 1, "tags": "php, theme customizer, api" }
gravity form login widget redirect i placed 'Gravity Forms User Registration Add-On's login widget in a page that registered users can login to my site. how do i redirect users to previous page that came from to login page after they submit login form?
here is the solution : add_filter('gform_user_registration_login_args','registration_login_args',10, 1); function registration_login_args( $args ) { $args['login_redirect'] = rgpost('login_redirect') ? rgpost('login_redirect') : RGForms::get('HTTP_REFERER', $_SERVER); return $args; }
stackexchange-wordpress
{ "answer_score": 1, "question_score": -1, "tags": "wp redirect, wp login form, plugin gravity forms" }
wp ajax return 0 I know its full of questions about this on SO, and I have read most and applied all possible solutions, thus its still not working. I have some ajax functions already up and working but for some reason this last one is not working. I have simple ajax request which sends header to admin-ajax.php: status is 200 (ok) and header is: `action:linked_post_image_grid` the code in my php file is really basic for testing: add_action('wp_ajax_nopriv_linked_post_image_grid', 'linked_post_image_grid'); add_action('wp_ajax_linked_post_image_grid', 'linked_post_image_grid'); function linked_post_image_grid(){ echo 'this is return message'; die(); } now for some reason this only and always returns 0
There's a simple alternative that sidesteps this issue entirely with a modern and easy to use interface, just use a REST API endpoint! So lets turn this: add_action('wp_ajax_nopriv_linked_post_image_grid', 'linked_post_image_grid'); add_action('wp_ajax_linked_post_image_grid', 'linked_post_image_grid'); function linked_post_image_grid(){ echo 'this is return message'; die(); } Into this: add_action( 'rest_api_init', function () { register_rest_route( 'buxbeatz/v1', '/linked_post_image_grid/', array( 'methods' => 'GET', 'callback' => 'linked_post_image_grid' ) ); } ); function linked_post_image_grid( $request ) { return "this is return message"; } Now you can visit `example.com/wp-json/buxbeatz/v1/linked_post_image_grid` and you'll get a JSON response of `"this is return image"`
stackexchange-wordpress
{ "answer_score": 3, "question_score": 0, "tags": "php, ajax" }
If I update WordPress my custom data will be deleted from the wp_users table? If I update WordPress my custom data will be deleted from the wp_users table? I add new custom field and store data to users at this field if I update WordPress and WordPress needs to update this table my custom field will be deleted?
It is possible, especially if the update includes changes to the user table. The only way to be sure is to test it, but for future reference: **Never modify the scheme of WordPress Tables** If you need to add additional information about something, WordPress provides meta, user meta, site meta, post meta, comment meta. You may know these as custom fields. For example: $value = get_user_meta( $user_id, 'example', true ); update_user_meta( $user_id, 'example', 'newvalue' ); $all_meta = get_user_meta( $user_id ); Adding columns manually to tables also bypasses the caching layer slowing things down, encourages writing manual SQL statements ( you could have used the `WP_User_Query` class! ), and stops the information being imported/exported ( custom post types get put in content exports, custom tables don't ) I recommend writing a small WP CLI command to fetch each user and store these columns as user meta instead
stackexchange-wordpress
{ "answer_score": 1, "question_score": 0, "tags": "custom field, mysql, table" }
Best way to develop a new theme on a live site, with new content? So I've worked with WP on many different occasions, but always either for a fresh install, or on a low-traffic live site with minor edits done in production. I'm going to be working on an overhaul of a site that is currently live. What I'm doing is not only creating a new theme, but also overhauling almost all of the content. I'm essentially creating a new site on the same WP install. If I was editing just the theme, I understand there are several ways to do this. However, for editing both theme and content while not disturbing a live site, what is the best way to go about this? Thanks!
You should never do work on a live site (of any size). Copy the existing site to another server, give it a temporary domain and block search engines in some way (robots.txt, http auth, ...). Depending on the work you do, you could stay connected to the same MySQL server, but it is usually recommended to also copy the tables to another db. Now you have an environment where you can do all your work without any fear that if anything breaks, the live site will suffer. Once you are finished, simply upload your themes and plugins to the live site, install them, et voilà. You can even use the regular theme update method for custom themes not hosted in the official repository.
stackexchange-wordpress
{ "answer_score": 3, "question_score": 0, "tags": "theme development, themes" }
How to get custom post type label and singular label from its slug? Let's say I have a Custom Post Type with the slug `books`. The label is `Readings` and the singular label is `Reading`. I want to display the Custom Post Type label in one of the custom post type's post. How can I achieve that? If I want to display a page title from its slug, I can use echo get_the_title(get_page_by_path('other-page-slug')); But I haven't found a clue to do this with custom post type.
`get_post_type_object()` will return, as the name suggests, an object that contains the post type information. You may want to `var_dump()` it to inspect it contents. You'll see that it includes (among other stuff) another object, `labels` that contains all the registered labels for the specific post type. $pt = get_post_type_object( 'books' ); // These two usually contain the post type name in plural. // They may differ though. echo $pt->label; echo $pt->labels->name; // This one holds the post type name in singular. echo $pt->labels->singular_name;
stackexchange-wordpress
{ "answer_score": 17, "question_score": 8, "tags": "custom post types, slug" }