INSTRUCTION
stringlengths
11
999
RESPONSE
stringlengths
0
999
SOURCE
stringlengths
16
38
METADATA
dict
Display Custom Taxonomy Name As A Shortcode On my WordPress site I have created a custom taxonomy named "game" which lists different gaming titles. I want to be able to display the names of these titles on my posts using a shortcode. Prior to creating a custom taxonomy, I was using WordPress' default categories taxonomy, and had the following code (found on stack exchange) working well: function shortcode_post_category () { $html = ''; $categories = get_the_category(); foreach( $categories as $category ){ $html .= '<h2>' . strtoupper($category->name) . ' KEYBINDS</h2>'; } return $html; } add_shortcode( 'category-keybinds', 'shortcode_post_category' ); From what I understand I need to change the `get_the_categories` to `get_the_term`(?) however with my very limited knowledge of `php` I cannot seem to get this to work on the new "game" taxonomy.
If you look at the source code of `get_the_category()` you see that this is not much more than a call to `get_the_terms ( $id, 'category' )`, where `$id` is the current post id. So, what you need is `get_the_terms ( get_the_ID(), 'game' )`. You need `get_the_ID`, because the `ID` is not passed to the shortcode as it is to `get_the_category`.
stackexchange-wordpress
{ "answer_score": 0, "question_score": 0, "tags": "customization, shortcode, taxonomy" }
include specific Pages to wp_list_pages with filter How can i make a simple filter to display only specific pages ( **include instead of exclude** ) as an output to wordpress pages widget? I made this code , but its not working function specific_pages($output) { $args = array( 'include' => array(147,12,32), ); $output = get_posts($args); return $output; } add_filter('wp_list_pages', 'specific_pages');
the corresponding hook would be < example code: add_filter( 'widget_pages_args','include_special_pages' ); function include_special_pages( $args ) { $args['include'] = array( 147, 12, 32 ); return $args; }
stackexchange-wordpress
{ "answer_score": 1, "question_score": 0, "tags": "filters, pages, widgets, wp list pages, include" }
Permalink slug no longer editable when using post_type_link filter I want to customize the output of the permalink for a custom post type, but I want the permalink to still be editable when editing a post. I'm using the `post_type_link` filter: add_filter( 'post_type_link', function( $post_link, $post, $leavename, $sample ) { if ( 'job' == $post->post_type ) { $post_link = ' . $post->post_name . '/'; } return $post_link; }, 10, 4 ); When this filter is active, it no longer shows the "Edit" button next to the permalink when editing the post. Even if I remove the custom permalink stuff and only have `return $post_link;` it still disables editing of the permalink. How can I customize the output and still keep the permalink editable?
> How can I customize the output and still keep the permalink editable? The following worked for me: $post_link = home_url( '/job/' . ( $leavename ? '%postname%' : $post->post_name ) . '/' ); I.e. If the `$leavename` is `true`, use `%postname%` in the URL. Otherwise, you may then use the actual post name/slug, i.e. the value of the `$post->post_name`. Additionally, I suggest you to use `home_url()` than hard-coding the site URL into the permalink. :) And I presume you will or have already setup the rewrite rules for the permalinks (`/job/<post slug>/` in the above example)? > Even if I remove the custom permalink stuff and only have `return $post_link;` it still disables editing of the permalink. I'm not getting that issue, so it's probably a theme/plugin conflict on your site -- try deactivating plugins and enable them back one at a time until you've found the culprit.
stackexchange-wordpress
{ "answer_score": 4, "question_score": 0, "tags": "permalinks, filters" }
get_results not returning anything What is the basic way to use $wpdb and get_results? This is my code: global $wpdb; $q="SELECT * FROM wp_usermeta WHERE meta_key = 'nickname' AND user_id = 771"; $result = $wpdb->get_results($q); echo $result; The query string is good because I can run it in phpmyadmin and it works fine. I am not getting anything back when run through page.
`$wpdb->get_results()` returns an array on success, so you can't simply `echo $result;`. Instead, you can use `foreach` to loop through the results and display whatever the data that you want to display: $results = $wpdb->get_results( $q ); foreach ( $results as $row ) { echo $row->meta_value . '<br />'; } But I can see that you're trying to select just _one row_ , so you'd want to use `$wpdb->get_row()` and not `$wpdb->get_results()`: $row = $wpdb->get_row( $q ); if ( $row ) { echo $row->meta_value; } But then again -- because `wp_usermeta` is the default table for WordPress users' meta, if you just want to retrieve the meta value, then there's a function you can (and should better) use -- `get_user_meta()`: echo get_user_meta( 771, 'nickname', true );
stackexchange-wordpress
{ "answer_score": 2, "question_score": 0, "tags": "wpdb, user meta" }
edit_tag_form_fields is depricated but tag_edit_form_fields doesn't work I need to create, retrieve, update and display a custom field in Wordpress tags. This code works for displaying the custom field, but its deprecated. function tag_edit_form_fields ( $term ) { ?> <tr class="form-field"> <th scope="row"><label for="term-colorpicker">Custom Field: </label></th> <td> <input type="custom_field" name="_custom_field" value=" <?php echo $custom_value; ?>" id="term-custom_term" /> <p class="description">This is a custom field.</p> </td> </tr> <?php } add_action('edit_tag_form_fields','tag_edit_form_fields'); Using the **new** function `{$taxonomy}_edit_form_fields` as `tag_edit_form_fields` doesn't seem to work.
While adding the tags to this stack exchange question, I added `tags` and the hint showed up as `post_tag`. ![enter image description here]( So, I tried add_action('post_tag_edit_form_fields','tag_edit_form_fields'); and it works!
stackexchange-wordpress
{ "answer_score": 2, "question_score": 0, "tags": "custom field, tags" }
Does a single theme license work on multisite? I am trying to create a multisite network and I want all of the sites in that network to look similar. So, I am planning to install a single premium theme in the whole network. My question is, will the same license work for all the sites in the network or will I have to purchase individual license?
That depends upon the seller of the theme. Contact them if their license is not clear about this. I ran across a couple of sellers of plugins (not sure about their themes) that have a special license specifically for multisite networks, while others say that if the sites are related in use (say one business' main site and the same business' blog site), you only need one license but if the sites are for different businesses, you need a license for each site. Whether the sites have their own domain names rather than just subdomain names can make a difference too.
stackexchange-wordpress
{ "answer_score": 3, "question_score": 0, "tags": "multisite, themes, premium" }
Count how many posts have a specified tag AND category I know how to count how many posts has a certain tag, or category For example: $term_slug = 'some-post-tag'; $term = get_term_by('slug', $term_slug, $post_tag); echo $term->count; **BUT!** Is there anyway to count how many posts that have a tag **AND** a specified category? I want to count how many posts that have the tag(slug) _"cat"_ and the category slug _"allowpost"_ Is this even possible? Edit: if possible, it would be good if this is manageable via some solution similarly my first script, because this is going to be used on search result pages, and **_different post pages_** , so adding something to the loop itself won't work..
This solved my issue, originally created by Mr. Prashant Singh @ WordPress forum $args = array( 'posts_per_page' => -1, 'tax_query' => array( 'relation' => 'AND', // only posts that have both taxonomies will return. array( 'taxonomy' => 'post_tag', 'field' => 'slug', 'terms' => 'your-tag-slug', //cat ), array( 'taxonomy' => 'category', 'field' => 'slug', 'terms' => 'your-category-slug', //allowpost ), ), ); $posts = get_posts($args); $count = count($posts);
stackexchange-wordpress
{ "answer_score": 0, "question_score": 0, "tags": "categories, tags, count" }
Escaping crashes my output When I add wordpress escaping code like esc_attr_e to below variable, it writes text instead of html code to my browser: <?php echo esc_attr_e( $redux_demo['editor-text-header-left'], 'hekim' ); ?> when I remove the escaping code, the variable gives html code. now, it gives the below text: <a href="#"><i class="fa fa-medkit text-thm2"></i> Help | </a><a href="#">Forum | </a><a href="#">Skype | </a><a href="#">Mon - Sat 9.00 - 19.00</a> How can I escape it correctly?
There are several issues here: 1. `echo esc_attr_e` should be just `esc_attr_e`, the `_e` means it already echo's 2. `esc_attr_e` is not just an escaping function, it's a localisation API, it's shorthand for `echo esc_attr( __(` 3. `esc_attr` strips out HTML, it's intended for use inside HTML attributes where HTML tags are not allowed. 4. You must never pass variables and dynamic values into localisation functions If you want to escape a string that contains basic HTML such as paragraphs etc, use `wp_kses_post`, e.g.: echo wp_kses_post( $redux_demo['editor-text-header-left'] );
stackexchange-wordpress
{ "answer_score": 2, "question_score": 0, "tags": "escaping" }
Delete post meta by serialized meta value I have some post meta entries which I like to delete from the database. The delete_post_meta() function seems the way to go: delete_post_meta( int $post_id, string $meta_key, mixed $meta_value = '' ) The problem: I have many entries with the same meta_key, so I'd like to specify the rows to be deleted by meta_value. But, the meta_value is serialized data. So how do I use `delete_post_meta()` to delete the post_meta by a specific value of the specialized data? For example, the serialized data: a:6:{s:2:"id";s:1:"1";s:4:"name";s:3:"PM1";s:5:"email";s:19:"[email protected]";s:3:"url";s:24:" How do I delete by serialized ID value?
Try below code to delete the post_meta by a specific value of the specialized data: $args = array( 'post_type' => 'post', 'meta_key' => 'any-meta-key', 'posts_per_page' => -1 ); $query = new WP_Query( $args ); if($query->have_posts()){ while($query->have_posts()){ $query->the_post(); $get_ID = get_post_meta($post->ID, 'any-meta-key', true); // Change the id value that you want to delete if ( !empty($get_ID['id']) && $get_ID['id'] == '1' ) { delete_post_meta($post->ID,'any-meta-key',$get_ID); } } } Don't forget to update the test meta key by your meta key.
stackexchange-wordpress
{ "answer_score": 0, "question_score": 0, "tags": "php, wp query, functions, customization, post meta" }
preg_replace specific Text to small latter strtolower Please i need to replace link with capital letter to small letter using wp function E.g let every text after `/get/` be replace with small letter. <a href=" => <a href=" <a href=" => <a href=" here is my function, I dont know where i am getting it wrong. however i am not good in wp. please correct me by posting the full correct code. function emailleftappend($content){ $findleft = '/get\/(?<=\/)([A-Za-z]+?) ([A-Za-z]+?)(?=\/">)/m'; $replaceleft = '$1-$2'; $content = preg_replace(strtolower($findleft), $replaceleft, $content); return $content; } add_filter('the_content', 'emailleftappend');
function emailleftappend($content){ $content = preg_replace_callback('/(?<=get\/)(.*?)-(.*?)(?=\/">)/', function ($m) { return sanitize_title($m[1]). '-'. sanitize_title($m[2]); }, $content); return $content; } add_filter('the_content', 'emailleftappend'); the above fixed the issue for me. another way is below. function emailleftappend($content){ $content = preg_replace_callback('/(?<=get\/)(.*?)-(.*?)(?=\/">)/', function ($m) { return slug($m[1]). '-'. slug($m[2]); }, $content); return $content; } add_filter('the_content', 'emailleftappend'); function slug($z){ $z = strtolower($z); $z = preg_replace('/[^a-z0-9 -]+/', '', $z); $z = str_replace(' ', '-', $z); return trim($z, '-'); } FINALLY FIXED
stackexchange-wordpress
{ "answer_score": 1, "question_score": -2, "tags": "functions, regex" }
Getting products information, in woocommerce based on products ID I have some ids like this $products = (1,2,3,4); I need to query woocommerce database to get info all products with that ids something like when im querying based on cateogory $products = wc_get_products(array( 'category' => array('Test'), )); Is possible to get based on ID, thanks?
You can get the `WC_Product` object for a product ID with the `wc_get_product()` function. So by using `array_map()` you can get the product data for those IDs like this: $product_ids = [ 1, 2, 3, 4 ]; $products = array_map( 'wc_get_product', $product_ids ); foreach ( $products as $product ) { echo $product->get_name(); }
stackexchange-wordpress
{ "answer_score": 0, "question_score": 0, "tags": "plugin development, woocommerce offtopic" }
Current WordPress Page Title as Search Parameter into A Tag <a href=“www.domain.com/s?=currentpagetitle”></a> i would like to include an affiliate link as a widget which inserts the title of the respective page as search parameter. <a href="www.amazon.com/s?=titleofthepage">Link</a> I have already created a shortcode in the functions.php with get_the_title function post_title_shortcode(){ $variable = get_the_title(); } add_shortcode('post_title','post_title_shortcode'); and it is called [post_title] However <a href="www.amazon.de/s?=[post_title]"></a> didn't work. Does anyone have any other idea how to make this happen?
Your shortcode is getting the title, but you haven't told it to return anything, so a small tweak should fix things: <?php function post_title_shortcode(){ return get_the_title(); } add_shortcode('post_title','post_title_shortcode'); ?> You could also continue setting `get_the_title()` to `$variable` and add a line to `return $variable`, but the above is the simplest, shortest option.
stackexchange-wordpress
{ "answer_score": 0, "question_score": 0, "tags": "php, widgets, url rewriting, urls, html" }
Why does Wordpress uses HTTPS for JS, CSS on EC2 I have migrated Wordpress site to EC2. Domain changes done in wp-config.php & in DB tables Also set AllowOverride All in Apache sites default conf. **Issue is:** Even though nowhere I'm using force SSL, still, on page load all assets are loaded with https. Since, I dont have SSL certificate active, all those resource show ERR_CONNECTION in Browser Console. As a result, The Pages also do not render properly
The Reason for the Issue was https-redirection plugin. I wasnt aware there was https-redirection plugin installed. So, even though i checked wp-config.php & .htaccess for SSL redirects, the plugin was forcing SSL for CSS/JSS/images. I renamed the plugin folder and everything is proper now. sudo mv /var/www/html/wp-content/plugins/https-redirection /var/www/html/wp-content/plugins/STOP-https-redirection
stackexchange-wordpress
{ "answer_score": 0, "question_score": 0, "tags": "ssl, https, http, amazon" }
All Titles and Menus changed to "CHILD THEME LOADED" I'm testing out a theme update on our website using a staged site created by WPStaging. That part seemed to work well. Then I upgraded the theme, created a child theme from it, and applied that child them to it. Now the title of every post, page, and even menu is "CHILD THEME LOADED" (see below). Yet when I edit a page or a post, the correct title is still there (in fact everything about the page or post looks correct in the editor). Any ideas? ![Example](
The UUA Theme offers a starter child theme which consists of an example `style.css` file and `functions.php` file. These files include a few lines of code to test if the child theme is loading correctly. You need to delete this test code from both files, which is identified in code comments. Specifically, this code in _functions.php_ : /** * Below is a test to confirm the parent theme is being overridden by the child. * If your page titles say, "Child Theme Loaded," the child theme is working. * After you confirm it's working, delete this function and filter. */ function uuatheme_title() { return "Child Theme Loaded"; } add_filter( 'the_title', 'uuatheme_title' ); And this code in _style.css_ : /** * Below is a test to confirm this stylesheet is being applied. * It turns all text to all caps. DELETE this after confirmation. */ body { text-transform: uppercase !important; }
stackexchange-wordpress
{ "answer_score": 2, "question_score": 0, "tags": "child theme" }
How to get a post views count using 'WordPress popular posts' plugin I am using 'WordPress popular posts' plugin, and I'm trying to **get post total views by ID** using: `wpp_get_mostpopular()` function. Is there anyway to achieve that? **or** is it even possible?
The `wpp_get_mostpopular()` will give you the posts with the most views. What you want to achieve is to get the post view count by passing a post id (or using it within the loop on the single page). There is a function which accepts post id as parameter: `<?php if ( function_exists('wpp_get_views') ) { echo wpp_get_views(get_the_ID()); } ?>` You can also show views in a specific time range. Have a look at: <
stackexchange-wordpress
{ "answer_score": 0, "question_score": 0, "tags": "plugins, php, theme development, themes, popular posts" }
Trying to modify the background of a form on a specific page Here's my CSS: .page-id-9399 body #gform_wrapper_3 { background-color: #363c42; } This is related to a Gravity Forms (contact form submission). I'd like the background of the FORM to be the color as above. I thought the above code would work because the Page ID os 9399 I think it is the reference "body" that throws this CSS snippet. Any ideas on how to fix it? Thanks
Another way of phrasing it is to just MOVE the body. The page-id class is applied to the body, so: body.page-id-9399 #gform_wrapper_3 { background-color: #363c42; } Would have worked
stackexchange-wordpress
{ "answer_score": 0, "question_score": 0, "tags": "css, plugin gravity forms" }
How to add more default colors? I just reinstalled my website with the same theme and now the other default colors are gone. Only black is left. Is there a way to add more default colors? ![](
You should be able to add more colors using the `add_theme_support` function as per the docs here add_theme_support( 'editor-color-palette', array( array( 'name' => __( 'strong magenta', 'themeLangDomain' ), 'slug' => 'strong-magenta', 'color' => '#a156b4', ), array( 'name' => __( 'light grayish magenta', 'themeLangDomain' ), 'slug' => 'light-grayish-magenta', 'color' => '#d0a5db', ), array( 'name' => __( 'very light gray', 'themeLangDomain' ), 'slug' => 'very-light-gray', 'color' => '#eee', ), array( 'name' => __( 'very dark gray', 'themeLangDomain' ), 'slug' => 'very-dark-gray', 'color' => '#444', ), ) ); I hope it helps!
stackexchange-wordpress
{ "answer_score": 1, "question_score": 0, "tags": "themes, block editor, color picker" }
WPML - Stop language redirection in initial load We have a multilingual website which is connected with English & Arabic using WPML plugin in WordPress. As a default behavior, the website is redirecting to /en/ version which I need to stop, but the same time, /en/ should not be removed from any menu links. The overall expectation is to stop the redirection only in initial load. For an example: If I type www.abcd.com, currently it redirects to www.abcd.com/en/ that needs to be stopped. I tried couple of workarounds advised in WPML forum but no luck. Thanks in advance for any help/suggestion.
Solution provided in WPML forum.
stackexchange-wordpress
{ "answer_score": 0, "question_score": 0, "tags": "plugins, multi language, plugin wpml" }
Sender e-mail address, for new order email to customer, is suddenly wrong I have an e-shop on WooCommerce version 4.1.1 and the past 2 days now it sends the new order email to customers from my personal administrator email, that belongs to another domain, instead of the [email protected] Before that, it was coming just fine with the information as shown in the screenshot that is in the WooCommerce setup. ![enter image description here]( Any ideas? Thanks! Vassilis
Found the culprit. It was the Mailchimp plugin. After I changed the address it worked.
stackexchange-wordpress
{ "answer_score": 1, "question_score": 0, "tags": "woocommerce offtopic, email verification" }
Find all the places where a block type is used I have a plugin installed that adds additional custom block types that can be used in the Gutenberg editor (the plugin is called Block Lab). Now I want to remove that plugin. For that, I have to remove all the used instances of those blocks. Is there a way to find all the occurrences of a used block type?
I know that this is not welcome here, but my only answer is that I can refer you to the following plugin. The plugin was released a few weeks ago and finds exactly the blocks used for your installation. Exactly what you need. <
stackexchange-wordpress
{ "answer_score": 3, "question_score": 1, "tags": "block editor" }
exclude particular category in api How do I exclude a particular category in the API? For all categories - I may use the following: _What if I need across all the categories except for category-10?_ I am using JavaScript at the front. **Thanks**
I just figured it out, just in case it might be helpful for anyone in future: There is an option available to exclude a particular category - categories_exclude So, the new rest API would be:
stackexchange-wordpress
{ "answer_score": 0, "question_score": 0, "tags": "posts, categories, rest api, api, json" }
Strange string in console from wpdb query I use this code: $search = $this->wpdb->prepare("WHERE (name LIKE %s OR tag LIKE %s)", '%'. $this->wpdb->esc_like($word) .'%', '%'. $this->wpdb->esc_like($word) .'%'); and in console i get: name LIKE '{4b9ad9b602bd32ff99324feebaa1883bb3a3e818f587b35198d4e48093375c78}night{4b9ad9b602bd32ff99324feebaa1883bb3a3e818f587b35198d4e48093375c78}' OR tag LIKE '{4b9ad9b602bd32ff99324feebaa1883bb3a3e818f587b35198d4e48093375c78}night{4b9ad9b602bd32ff99324feebaa1883bb3a3e818f587b35198d4e48093375c78}' how i can remove this strange string?
That is a _placeholder escape string_ generated by `wpdb::placeholder_escape()` which is used by `wpdb::add_placeholder_escape()` and which is called by `wpdb::prepare()`. So it is safe to keep those escape strings, but there is a `wpdb` method for removing them: `wpdb::remove_placeholder_escape()`: // In your case, you'd use $this->wpdb in place of $wpdb. $query = $wpdb->add_placeholder_escape( 'LIKE %night%' ); $query2 = $wpdb->remove_placeholder_escape( $query ); var_dump( $query, $query2 );
stackexchange-wordpress
{ "answer_score": 2, "question_score": 1, "tags": "query, wpdb" }
How to display strikethrough text in button text (for special offer) I'm trying to create a `"Purchase for ~$20~ $1"` button (using Elementor). I'm not sure how to achieve the strikethrough. Also I would like the `$1` to be in bold/red. I suspect I need to dynamically replace the contents of the button using JS. But I'm not sure how to go about that or even if it's the best approach. Alternatively I could use an image, I guess. What would be a sensible approach?
It turns out that it is possible to use custom HTML inside the text box when you enter the text for the button: Special offer: <span style="text-decoration:line-through">$20</span> <span style="color:#f00">$1</span>
stackexchange-wordpress
{ "answer_score": 0, "question_score": 0, "tags": "customization, buttons" }
Comparison operator != not working in <select> field Please i want to ensure only male or female is selected in the dropdown if not fail the form but my validation keeps returning false even if male or female is selected. Html <select name="gender"> <option value="Male">Male</option> <option value="Female">Female</option> <option value="Nonesense" selected>Nonesense</option> </select> Here is the php code if ( isset( $_POST['submit'] ) ) { if ( $_POST['gender'] != 'Male' || $_POST['gender'] != 'Female' ) { echo 'sorry it must be either male or female'; return ''; } }
The reason it does not work is due to a logic error, which becomes obvious if you follow the code manually for each value It has nothing to do with the `select` element, or special behaviour of `!` or `!=` So lets look at your conditional: $_POST['gender'] != 'Male' || $_POST['gender'] != 'Female' * if ( gender is not male ) OR ( gender is not female ) * then complain it must be male/female So lets say that the gender is male: * if ( false ) OR ( true ) * then complain it must be male/female Since true is true, it resolves to `if true` and the complaint appears. So it appears, the problem is a misunderstanding of how `OR` works `a OR b` <\- this resolve to true if either 'a', 'b', or both a and b are true. What I think you meant was: `if ( gender is male OR gender is female ) is not true` rather than `if ( gender is not male ) OR ( gender is not female )` **But finally, this question and answer has nothing to do with WordPress.**
stackexchange-wordpress
{ "answer_score": 0, "question_score": 0, "tags": "php, html" }
WooComerce shows blank site (Shop) The site I set WooComerce to use as the shop is blank (white), I enabled debuggng mode (`define('WP_DEBUG', true);`) but no errors are shown. I tried to using a new Site for the shop but the same. The rest of the Website works perfectly fine, as does the checkout, and other WooComerce pages. The ' _status_ '-tab of the WooComerce-Plugin shows that everything is allright. I'm pretty new to WooComerce so is there a key setting I'm missing or something? The Shop worked fine a few Weeks ago but I just noticed the blank site. Thanks for your advice!
Finally fixed it. An outdated, Theme spefic Woocomerce Extension caused the Problem. Had to update the files manually... I don't now if it helps someone else but this was the fix for me.
stackexchange-wordpress
{ "answer_score": 0, "question_score": 1, "tags": "woocommerce offtopic" }
how to change site tag line for particular pages I need to change my site tag line. Basically, this is school site we create for xyz higher sec school and ABC Nursery school; so I need to add both as a tag line in my site if I use xyz higher sec school I can't be able to use ABC NURSERY for those particular pages. I need to change tagline for around only 6 pages; kindly suggest me for that.
If your theme is using the WordPress site tagline, you should be able to filter it. `get_bloginfo( 'description' )` will call `get_option( 'blogdescription' );`, and we can filter the value of an option using the `option_{$option}` hook. Let's suppose, for this code sample, that you want to change the tagline on 3 pages, with the titles **Kindergarten** , **Nursery School** , and **Babysitting**. add_filter( 'option_blogdescription', 'wpse368031_change_tagline' ); function wpse368031_change_tagline( $tagline ) { $pages = array( 'Kindergarten', 'Nursery School', 'Babysitting' ); if ( is_page( $pages ) ) { $tagline = 'ABC Nursery'; } return $tagline; } Try adding this code to your active theme's `functions.php` file. ## Reference * `get_bloginfo( 'description' )` * `option_{$option}` hook * `is_page()`
stackexchange-wordpress
{ "answer_score": 1, "question_score": 1, "tags": "navigation" }
Order All Pages table in administration In administration, in the "All Pages" section, each time I add a new page the table is refreshed order by page Title. I reorder the table clicking on "Date" column to keep working on the last updated pages, but every refresh the order change again to Title. I cannot find any plugin or way for Wordpress to remember the last order selected. Is there any way to achive this? TL;DR I want Wordpress to remember the order of "All Pages" in the administration.
There is no plugin for that. But you can achieve this by using filters. Add following code to you theme's `functions.php` file: /** * Order Admin Page List by Date by Default */ add_filter('pre_get_posts', 'my_set_page_order_in_admin' ); function my_set_page_order_in_admin( $wp_query ) { global $pagenow; if ( is_admin() && $_GET['post_type'] == 'page' && 'edit.php' == $pagenow && !isset($_GET['orderby'])) { $wp_query->set( 'orderby', 'date' ); $wp_query->set( 'order', 'desc' ); } }
stackexchange-wordpress
{ "answer_score": 1, "question_score": 0, "tags": "admin" }
Staging Sites: What to push through? I have a staging site where I am improving the theme and layout, adding a couple of plugins to add a slide in navigation bar etc. The issue is that on the live site, people are signing and purchasing membership, plus some memberships are expiring etc. Oh and I'm with siteground. My question is, how do I push through my staging site so that the users' data on the live site persist? Is all user data stored in the same table? When pushing the new site is it possible to only push through the database tables that I have made changes to due to my development, leaving all other tables in tact from the live site?
Siteground should be able to tell you if your sites share a DB (or it should be evident from whatever control panel they provide). That said, it's generally not advisable to mess with the DB of a live site. Make your changes and configure your plugins on stage, then when you're happy, replicate that work on your production site - at a low-traffic time, if necessary.
stackexchange-wordpress
{ "answer_score": 2, "question_score": 0, "tags": "staging" }
What is the use of $content_width? In the requirements of Envato I saw that they require a `$content_width` to be set. I searched for it on the internet but can't really understand why? I don't use it and the theme is responsive. If I only declare the `$content_width` and never use it, what value should I give it?
`$content_width` is used to set the default width of embeds, for situations when an element needed to specify a width. This is how WP knew the width of the main content area. However, this was back before the push for responsive design, and modern CSS with fluid embeds and responsive breakpoints. So it isn't needed much but it can still result in odd embeds if you set a bad value. Content width sometimes gets used in other edge cases too, but that was the main use case and its reason for being. So I suggest: * Figure out the content width on the most common desktop resolution, and use it to set `$content_width` in `functions.php` * Then, apply CSS to adjust embeds responsively/fluidly as you would normally do
stackexchange-wordpress
{ "answer_score": 3, "question_score": 0, "tags": "variables, globals, content width" }
Wordpress 404 all pages except home I know this question might be a repeat or duplicate of another post. I've been getting this error after shortly migrating the domain from `http` to `https`. I've been following multiple questions and answers like this one right here but none of them seem to work. Solutions i've tried: -> disable all plugins and enable them again -> change `.htaccess` file to the default wordpress -> change permalink structure to the default one again. None of the above solutions worked for me now, although they worked in the past for a different website. All pages give me `404 document not found in the server` except the homepage. thanks in advance! EDIT: The problem does not happen if i use the default permalink structure and if use the following code in the wp-config: define('WP_HOME', ' define('WP_SITEURL', ' //define('WP_DEBUG', true); define('CONCATENATE_SCRIPTS', false);
Fixed it by changing the website url in the database on the table `wp_options` Seems like it didn't change even after i change the url in the backend, i had to change it manually.
stackexchange-wordpress
{ "answer_score": 0, "question_score": 0, "tags": "404 error, server" }
Custom author url and page for another role I would like to create a custom url and a separate or duplicate the author.php template for another custom role w/o using plugins. I found this related topic but it just modify the author url Override default url for author pages? Something like: `mydomain.com/author/foo` for all the default roles and `mydomain.com/member/john` for the new custom role
Hi You can create a user roles and create a dynamic author base for each role from setting. Use the below github repo: < ![enter image description here](
stackexchange-wordpress
{ "answer_score": 0, "question_score": 0, "tags": "url rewriting, user roles, author, author template" }
How to convert objects into arrays Please i need assistance in converting objects that is returned from $wpdb->get_results into arrays so that i can call them values like $query['username'] instead of using $Query->username because my method of doing it is not flexible enough and it makes me write many codes by manually creating those column as array just like this code below `$data = array('username = $query->username, email = $query->email');` but i believe there is a simple way to do this automatically without having to retype all column names one by one
`$wpdb->get_results` has a second parameter that lets you specify what kind of return value you want: For example: $data = $wpdb->get_results( $query, ARRAY_A ); Here you get an associative array back.
stackexchange-wordpress
{ "answer_score": 1, "question_score": 1, "tags": "php, mysql, array" }
Don't update modified post date when user add a product review or comment? I am using WooCommerce and I added the following code on `content-single-product.php`template to show last update of product: <p class="data-label">Updated</p> <p class="info"> <?php echo get_the_modified_time( 'F j, Y' ); ?> </p> On single product pages I have enable reviews tab and comment tab so customer can add comment on a product. The problem is when user add new review or comment to product, the last update date for the product is changed to the date of its comment. I don't want to change the last update date of product when user add new comment on any product.
WooCommerce seems to update the 'last modified' value of a product on every change. If you want to take a look at the source code, go to `woocommerce\includes\data-stores\class-wc-product-data-store-cpt.php` and check the function `update`. This solution seems to work, however it could be improved to make sure it doesn't mess up with anything else. Basically checks if the request has info of a comment and filters the query that modifies the post date to skip it. I didn't find any earlier hook than the `query` filter. add_filter('query', function($query){ if(isset($_POST['comment']) && strpos($query, 'post_modified')){ return ''; } return $query; });
stackexchange-wordpress
{ "answer_score": 0, "question_score": 0, "tags": "php, posts, woocommerce offtopic, date" }
Adding Custom Endpoint in WordPress Rest API I have been working on custom WordPress rest API Endpoint. Goal is to create a WordPress custom route in this route i want to get Category Id and convert it to Category Name. I have written the function but its returning null for the category Id. The function simply get the categories of the WordPress and register the route.How Can I get the all Categories Id and convert category Id into category name. function w_categories() { $categories = get_categories(); $data = []; $i = 0; foreach ($categories as $category) { $data[$i]['id'] = $category->ID; $i++; } return $data; } add_action('rest_api_init', function () { register_rest_route('w/v2', 'trending', [ 'methods' => 'GET', 'callback' => 'w_categories', ]); });
Instead ID you should use cat_ID $data[$i]['id'] = $category->cat_ID; get_categories() return list of category objects with: "term_id": 7, "name": "default", "slug": "default", "term_group": 0, "term_taxonomy_id": 7, "taxonomy": "category", "description": "", "parent": 0, "count": 11, "filter": "raw", "cat_ID": 7, "category_count": 11, "category_description": "", "cat_name": "Analiza", "category_nicename": "default", "category_parent": 0
stackexchange-wordpress
{ "answer_score": 0, "question_score": 0, "tags": "plugins, custom field, rest api" }
Can Wordpress admin user + database credentials be used to gain Cpanel or FTP access? Trying to figure out if deleting admin user and changing database password will be enough to secure the website afterwards.
Security of your WP site is more than that (admin user, database password), although that is a good start. I'd * create admin-level user that is not named 'admin', with a strong password. You could even change the user id so that it's not #2 (it's easy enough to enumerate users by id). * create a strong password for your database * use a different prefix for your database * create strong credentials for your hosting place * create strong credentials for FTP users (and only use SFTP) * remove features (plugins/themes) that you are not using * keep everything updates: WP, themes, plugins, PHP * use PHP version 7.x+ * regular backups - off-host * htaccess security * disable RPC And that's probably just the beginning. There are good resources on the WP site (and other reputable sites) for WP security - ask the googles/bings/ducks .
stackexchange-wordpress
{ "answer_score": 0, "question_score": 0, "tags": "security" }
Calling plugin function inside custom plugin for onclick event I want `testFunction()` to call `check()` that i created in my plugin php when i click **My Button**. How do i make it work ? <?php function createButton() { echo '<button onclick="testFunction()">My Button</button>'; } function check() { alert("Works"); } function my_php_function() { echo '<script> function testFunction() { check(); } </script>'; } add_action( 'wp_footer', 'my_php_function' );
AJAX is the solution. For more info: <
stackexchange-wordpress
{ "answer_score": 0, "question_score": 1, "tags": "plugins, functions, hooks, actions, events" }
Woocommerce REST API allow normal users make an order We are making an application that can make an order from the mobile for Woocommerce API, when I used a loggedin user with token for validate the authentication, its showing error: Sorry, you cannot view this resource. But when I am using Administrator, its works. How I can make an other for regular user (non-admin)?
I found our my solution by customize "woocommerce_rest_check_permissions"
stackexchange-wordpress
{ "answer_score": 0, "question_score": 1, "tags": "woocommerce offtopic, api" }
How to retrieve current page WP_Query arguments? # Context I'm developping a plugin showing geolocated posts on a leaflet map. **I want to add a shortcode parameter to show a map with only the current loop posts' markers.** That feature would be great on the search result page for exemple! # Question **Is there a way to get the current page WP_Query arguments?** I want to get those arguments to create a new WP_Query and add some more to filter only geolocated posts. I don't know if it's possible at all, I always create new WP_query objects from scratch. Thank you!
Have you tried using `$wp_query` ? global $wp_query; var_dump($wp_query->query_vars); For a single variable, you can use get_query_var Or you could try just dumping the `$_POST` , `var_dump( $_POST );` Or maybe `var_dump( $GLOBALS['post'] );`
stackexchange-wordpress
{ "answer_score": 7, "question_score": 3, "tags": "wp query, loop, shortcode" }
How to create Custom Theme in Wordpress 5.5.3 I want to create custom theme in word-press from scratch so can you have the idea about custom theme folder structure and development steps so please help me. Thank You in Advance.
There are countless guides online, just search 'Wordpress Theme creation' on Google. A good place to start would be < For folder structure I suggest you use a 'Wordpress Theme Boilerplate', you can generate one here: < but there are loads of other options. More are listed here: < Or if you don't know php, you could try this: < Entering the question you have asked here on Google will give you many more results which might fit your needs even better.
stackexchange-wordpress
{ "answer_score": 2, "question_score": -1, "tags": "theme development" }
How to extend a plugin like we do a theme? In **WordPress** we can easily extend a parent theme by creating a **child theme**. How can we create a child plugin from parent plugin? I search a lot and people suggested to use actions and hooks but what if a plugin doesn't provide hooks and actions? Actually I want to extend LearnDash plugin. I want to extend it's functionality in my child plugin. So that if any updates comes in plugin, it shouldn't conflict with our custom changes. But currently I have no idea how to extend it?
There’s no standard method apart from hooks, and it’s up to the developer of the original plugin to add and support these. If the plugin is extendable they will have developer documentation (LearnDash’s is available here). The specifics will depend entirely on the plugin and how they’ve chosen to allow it.
stackexchange-wordpress
{ "answer_score": 2, "question_score": 2, "tags": "plugin development" }
How to add some lines to the wp-login.php header via functions.php? I have no idea what function to use to add this line to the wp-login.php header: `<meta name="viewport" content="width=device-width, user-scalable=no">` I have tried `add_action('wp_head', 'change_this_name_of_your_function');` until I have found out that the `wp-login.php` file uses a different header. Thanks for your help!
`wp_head` is for adding stuff in the `head` of the public/non-admin side of a WordPress site. For the standard login page for the admin screens, you can use `login_head`: add_action( 'login_head', function () { echo '<meta name="viewport" content="width=device-width, user-scalable=no">'; } );
stackexchange-wordpress
{ "answer_score": 1, "question_score": 0, "tags": "headers" }
Is there a tool to see every WordPress site that's using a particular plugin? Is there a tool to see every WordPress site that's using a particular plugin? For example: if I wanted to know every website in the world that is currently (or historically) using Yoast SEO. I realize this would probably be a third party tool, so I don't know if it's appropriate for this forum. But, I figured it's a good place to ask seeing as it's related to WordPress.
I dont think Beyond Multisite is going to do it. when you look at a site that is using Yoast you will see that it loads 'yoast.js' The best idea I have is to use a site like publicwww.com (free for first 3M pages) to provide a list of all sites that it knows also using that file. < That link should work. This may not be ALL the sites it is only the sites that the page has crawled / discovered. There are prob other sites with this ability. Hope this helps. Cheers,
stackexchange-wordpress
{ "answer_score": 0, "question_score": 0, "tags": "plugins, third party applications" }
Plugin to allow for recurrent subscription + exclusive content Recently my step-mom lost her freelancing gig with a couple of newspapers. She ran a fairly prominent feature about two shows, and decided to take her writing elsewhere, setting up her own website to use. She did some initial probing of her userbase and they all said they'd be willing to pay $5 or so a month to be able to read the stuff that my step-mom writes, but obviously we don't want for these posts to be viewable to anyone outside of the subscribers or herself. Anyone here use anything? I've seen something to do with woocommerce pop up, and quite a few other places that charge a good bit to be used, but I have no experience with them so I'm hesitant to commit to one I have no feedback about. Thanks in advanced!
You probably need a couple plugins to do this. I use Woocommerce for just about everything - there is a ton of plugins and a lot of support online. Get Woocommerce for free through the wordpress repository. Set up your store through there. Then you will need Woocommerce subscription & Woocommerce Membership - it is the best to use for something like this. Get a free membership over at gpldl.com - a great site where you can download these woocmmerce plugins for free once you are signed up. Once signed up - go to < and get "WooThemes Subscriptions WooCommerce Extension" and install it. Finally - you will want "WooCommerce - Memberships WooCommerce Extension" which can also be downloaded at gpldl.com. Once you have these plugins - you should be able to follow the setup instructions and get your membership site up and running.
stackexchange-wordpress
{ "answer_score": 1, "question_score": -1, "tags": "plugins, subscription" }
Can a Custom Taxonomy be named "category" like normal Posts? Is it fine to call a Custom Taxonomy (created to store Custom Post Type) "Category" like it is already the case for _normal_ Posts, and to use all the terminology ("Categories", "Create a new category", etc.) ? I mean, are there any risk of instability or compatibility issues if I do so ? Like for example : taxonomy overridden, etc…
No. "Category" is one of WordPress reserved terms. < **Reserved terms** * attachment_id * author * author_name * calendar * cat * **category** * category__and * category__in * category__not_in
stackexchange-wordpress
{ "answer_score": 0, "question_score": 1, "tags": "custom post types, custom taxonomy" }
Disabling the X-Redirect-By response header Is there a clean way to not have WordPress send the `X-Redirect-By` response header when redirects happen? I'd like to disable it in order not to expose information about our software stack. Something I can hook into `functions.php` perhaps?
This line added to functions.php (ideally in a child theme, or a plugin) will remove it: add_filter( 'x_redirect_by', '__return_false' );
stackexchange-wordpress
{ "answer_score": 4, "question_score": 3, "tags": "redirect, headers, http" }
Wrong Canonical url link I have a weird problem. I have a page that changed URL (because it's parent changed name). Example Link https:www.mysite.com/my-services/service-1 is now: https:www.mysite.com/services/service-1 the canonical url however is still the original one: https:www.mysite.com/my-services/service-1 which is wrong. (it should be the new link) This is what I tried: * I had the redirection plugin to handle the redirect, but have switched that one iff > does not solve the problem * I have switched of Yoast > doesn't help * I switched on Yoast again - and explicitely changed the canonical link in the Yoast SEO section of th page > that solves it. However I don't want to manually have to change a canonical like this. Is there a better solution? Am I missing something? Can I regenerate canonical tags in batch? So many questions - is there someone with an answer? Thanks a lot in advance, Ingrid
You need to reset your indexables. There are a couple of ways to do this - you can use a WP-CLI command (`wp yoast index`), or you can use the Yoast Test Helper plugin. If you install the Yoast Test Helper Plugin, you can go to Tools > Yoast Test. In the "Yoast SEO" box with a bunch of buttons, use the "Reset Indexables tables & migrations" button to flush them. You can then uninstall the plugin, remove your manually-entered canonical URL, and the default (autogenerated) canonical URL will be fixed. Theoretically, anytime you make a change such as changing a parent page URL, that should trigger Yoast to automatically update its indexables. So it may be worth opening a GitHub issue so they're aware this didn't happen as intended.
stackexchange-wordpress
{ "answer_score": 2, "question_score": 1, "tags": "plugin wp seo yoast, rel canonical" }
In the media Rest API, what is "missing_image_sizes"? I'm trying to understand the media rest-API. The last item in the schema: ![missing_image_sizes]( What is this? Missing _vis-a-vi_ what exactly? Is this information used somehow by default? Reference: developer.wordpress.org/rest-api/reference/media
### Basically, it corresponds to missing thumbnails or custom-sized images in your media library. And it's (by default) _a private field_ in the REST API and the value is one or more image sizes as returned by `wp_get_registered_image_subsizes()`. And the function which is used with that field is `wp_get_missing_image_subsizes()` which returns: > _(array)_ An array of the image sub-sizes that are currently defined but don't exist for this image. So for example, if you added a new image to your library and then — after the image's thumbnail and other custom sizes are generated — you programmatically called `add_image_size()`, then you'd likely see the `missing_image_sizes` field containing the newly added image size when you request the image data through the REST API. E.g. * Request URL: (GET method) ` * Sample response for _missing_image_sizes_ : `"missing_image_sizes":["my_size"]`
stackexchange-wordpress
{ "answer_score": 2, "question_score": 0, "tags": "uploads, media, rest api" }
How do I associate a domain, with an existing WordPress blog? I've purchased a domain for my daughter, who wants it to use her blog on Wordpress.com. What isn't clear to us is how to associate the domain I've purchased from the registrar, to her Wordpress.com blog. How do we do that?
This is reasonably well documented on <
stackexchange-wordpress
{ "answer_score": 1, "question_score": 0, "tags": "wordpress.com hosting" }
Disable all resizing and compression How do you successfully disable all image compression and resizing? I would like Wordpress to use the image exactly as it is uploaded. same pixel dimentions, same quality. I have gone down the route of adding to **functions.php** multiple strings that change the thresholds and the quality like... add_filter( 'jpeg_quality', function() { return 100; } ); No joy. There are multiple threads on this topic across the net, lots of similar suggestions, none of them work/work with the recent Wordpress release. Has anyone been able to achieve this? Thanks
Turns out I was never too far off. Adding this to your **functions.php** will stop all resizing and compression of images uploaded to the media folder add_filter( 'big_image_size_threshold', '__return_false' ); add_filter( 'jpeg_quality', function($arg){return 100;} ); update_option( 'medium_size_w', 9000 ); update_option( 'medium_size_h', 9000 ); update_option( 'large_size_w', 9000 ); update_option( 'large_size_h', 9000 ); Hope this helps someone Thanks
stackexchange-wordpress
{ "answer_score": 0, "question_score": 1, "tags": "images, uploads, compression" }
"BS_" rows in postmeta table I am pruning my WordPress site's MySQL database and noticed that there are thousands of rows in the `postmeta` table with the prefix "BS_". BS_author_type BS_guest_author_name BS_guest_author_url BS_guest_author_description BS_guest_author_image_id Are these generated by WordPress or by a plugin that I might have added and removed before? I tried googling the meta-keys as well as the prefix `BS_` and the only result I got is a Romanian webpage with random code and a few images on it.
They're from wordpress.org/plugins/guest-author. The keys suggested they were from a guest author plugin, so I searched Google for guest author plugins, opened the first result, browsed the code, and found that it uses those keys.
stackexchange-wordpress
{ "answer_score": 0, "question_score": 0, "tags": "database, post meta, mysql, wpdb" }
How can i create a function tag in my plugin I want to know how what function or hook i can use to create a php function that executes as tags like this `[block] content to be blocked[/block]` my function will start with [start] afftected content goes here [/end] anything inside the start tag and the end tag will be affected by my function, it could a simply unset or hide or exclude kind of function, please i need to include this in my plugin, any suggestions.
You are looking for Enclosing Shortcode. Here is an example of how you can achieve this. function example_shortcode($atts = [], $content = null) { // do something to $content // run shortcode parser recursively $content = do_shortcode($content); // always return return $content; } add_shortcode('example', 'example_shortcode'); Now you can use it like `[example] Here is my content [/example]` Read more about `add_shortcode()` here
stackexchange-wordpress
{ "answer_score": 0, "question_score": 0, "tags": "php, functions, conditional tags" }
Display posts from one network site on another I've got to be missing something very basic here. I want to display posts from one site on another. No custom queries (yet), just the plain old posts. if ( get_current_blog_id() == 1 ) : // do regular main site stuff; elseif ( get_current_blog_id() == 6 ) : switch_to_blog( 1 ); // pull in posts from main blog if ( have_posts() ) : while ( have_posts() ) : the_post(); get_template_part( 'content/post' ); endwhile; endif; restore_current_blog(); else : // nothing special endif; When I try this, I get the post data from the site I'm trying to pull into (site 6) rather than site 1. I can echo get_current_blog_id() while in the loop, and it tells me I'm in site 1, but the post content ends up coming from from site 6.
You are looping through the posts queried before your `switch_to_blog()` statement. Your code appears to be from a page template which is executed AFTER the main query has run. To be clear, the main query is run before the template code is executed. Switching to another site after that does not update the query, therefore your loop is iterating through the original blog (#6). Try something like this instead: switch_to_blog( 1 ); // pull in posts from main blog $query = new WP_Query(); if ( $query->have_posts() ) { while ( $query->have_posts() ) : $query->the_post(); get_template_part( 'content/post' ); endwhile; wp_reset_postdata(); } else { // none were found } restore_current_blog(); EDIT: updated to use OP's original loop and template part. EDIT 2: clarified order of execution in the first few sentences.
stackexchange-wordpress
{ "answer_score": 0, "question_score": 0, "tags": "multisite, switch to blog" }
How to get_term_meta on single custom post? I added custom image and icon to my custom taxonomy, and I know how to display it in the front end in the taxonomy template page. $headImageId = get_term_meta( get_queried_object_id(), 'category-image', true ); $headImageUrl = ( ( $headImageId != '' ) ? wp_get_attachment_url( $headImageId ) : '' ); But how do I call it in my single post template? I want to use the image from the taxonomy term the custom post belongs to as a header background. I can't get my head around this..
You will need to use `get_the_terms()` to get the taxonomy terms associated with the post and loop through them until you find one that has an image set: $post. = get_queried_object(); $terms. = get_the_terms( $post, 'taxonomy_name_here' ); $image_url = null; if ( $terms && ! is_wp_error( $terms ) ) { foreach ( $terms as $term ) { $attachment_id = get_term_meta( $term->term_id, 'category-image', true ); if ( $attachment_id ) { $image_url = wp_get_attachment_image_url( $attachment_id, 'full' ); break; } } } if ( $image_url ) { // Output image as needed. }
stackexchange-wordpress
{ "answer_score": 1, "question_score": 0, "tags": "custom post types, custom taxonomy, custom field, templates, advanced taxonomy queries" }
Change password notification email By default, when customer changed their password using "Lost your password?" link, an email notification saying "`Password changed for user: ***`" will be sent to Admin's email address. Is there way to change the email address recipient without changing the website's admin email address?
Yes, the email properties are filtered through wp_password_change_notification_email before it is sent (code here), which you can hook to modify them e.g. function set_password_change_notification_email_to( $email, $user, $blogname ) { $email[ 'to' ] = '[email protected]'; return $email; } add_filter( 'wp_password_change_notification_email', 'set_password_change_notification_email_to', 10, 3 );
stackexchange-wordpress
{ "answer_score": 0, "question_score": 0, "tags": "woocommerce offtopic, password" }
Troubleshooting Admin_Notice I have this code at the top of a plugin: function my_mwe_admin_notice(){ echo '<div class="notice notice-error">'; echo '<h1>Notice this.</h1>'; echo '</div>'; } add_action( 'admin_notices', 'my_mwe_admin_notice' ); Where and when is this notice supposed to appear? I can't find it. Have also tried adding `global $pagenow` and `if ( 'plugins.php' == $pagenow ) { // also index.php, etc...` What am I missing?
Yup. I threw my test code in the top of the Hello Dolly plugin and there was the notice. That's when I remembered that I was calling it within a namespace: So needed to referenced that so the WP action could access it: namespace My_Plugin; function my_mwe_admin_notice(){ echo '<div class="notice notice-error">'; echo '<h1>Notice this.</h1>'; echo '</div>'; } add_action( 'admin_notices', __NAMESPACE__ . '\\my_mwe_admin_notice' );
stackexchange-wordpress
{ "answer_score": 0, "question_score": 0, "tags": "plugins, notices" }
Why Query is returning empty array? I am trying to execute a query using the below code but I'm getting empty array in **var_dump**. global $wpdb; global $post; $slug = $post->post_name; $course = $wpdb->get_results( "SELECT * FROM wp_posts where post_name = $slug" ); var_dump($course);exit; // If I run the same query in **PHPMyAdmin** it returns 2 records: SELECT * FROM wp_posts where post_name = "course-1"; // this returns 2 records I also vardump `$slug = $post->post_name;` in code and it is return the below string(8) "course-1"
you may need to wrap $slug in quotes $course = $wpdb->get_results( "SELECT * FROM wp_posts where post_name = '$slug'" );
stackexchange-wordpress
{ "answer_score": 2, "question_score": 0, "tags": "posts, wp query, query, wpdb, table" }
Add custom parameters in SoundClound embed I use oEmbedd functionality of WordPress. All work fine but I need to set custom parameters in the iframe So I try this without success : function my_oembed_fetch_url( $provider, $url, $args ) { // You can find the list of defaults providers in WP_oEmbed::__construct() if ( strpos( $provider, 'soundcloud.com' ) !== false) { if ( isset( $args['show_artwork'] ) ) { $provider = add_query_arg( 'show_artwork', absint( $args['show_artwork'] ), $provider ); } } return $provider; } wp_oembed_get(' array('show_artwork' => 'false')); What's wrong ? Thank you in advance
Have you added the filter in your code to utilize "my_oembed_fetch_url" ? add_filter( 'oembed_fetch_url', 'my_oembed_fetch_url', 10, 3 );
stackexchange-wordpress
{ "answer_score": 1, "question_score": 0, "tags": "embed" }
How to not cache nonces with WP Rocket? We have a system where we pass a nonce from a PHP-script on the server to an AJAX-call running client-side, and then back again to check the validity of the request. This nonce is cached, and we can't figure out how to exclude it. We had cache time set to 10 hours but have since reduced it to 8 hours. But let's say the nonce is renewed at 12 AM and the cache is renewed at 10 AM, we still have six hours of the nonce not working even with 8 hours cache. How do we fix this?
Find the specific AJAX call URL and prevent that being cached with the WP-Rocket advanced rules settings. < As per your comment, you need a strategy for not having the nonce in a file that can be cached such as javascript files, so as you said, use PHP to generate the nonce and pass it outside of the javascript file. ![enter image description here](
stackexchange-wordpress
{ "answer_score": 0, "question_score": 0, "tags": "cache, nonce" }
How can I prevent a function from loading in the admin screens? When I add this code to my theme's `functions.php` file, it crashes my admin panel. How can I prevent it from loading in the admin screens? //add_action('init', 'hekim_sticky_header'); // I want load this only if it is not admin panel
You can use the `is_admin()` function to check: add_action( 'init', 'hekim_sticky_header' ); function hekim_sticky_header() { if ( is_admin() ) { return; } // Rest of your function goes here. }
stackexchange-wordpress
{ "answer_score": 1, "question_score": 0, "tags": "wp admin, actions" }
file_get_contents | escaping doesnt show the page I have below code.`echo $FileContents;`shows the page which comes the php variable correctly, but the escape function which is `<?php esc_html( $FileContents ); ?>`didnt show anything. How can I escape it correctly and show the page? <?php global $redux_demo; ?> <div class="row"> <div class="col-md-12 ulockd-mrgn1210"> <?php $FileContents = file_get_contents($redux_demo['text-location-service-details']); ?> <?php echo $FileContents; ?> <?php esc_html( $FileContents ); ?> </div></div>
Well, `esc_html()` doesn't echo/display the return value (escaped string), so you need to call `echo` manually: echo esc_html( $FileContents ); ## Update If you actually want to filter the list of allowed HTML tags in the variable's value, then you can use the WordPress' KSES functions like `wp_kses_post()` and `wp_kses_data()`: echo wp_kses_post( $FileContents ); echo wp_kses_data( $FileContents ); // allows basic HTML by default
stackexchange-wordpress
{ "answer_score": 0, "question_score": 0, "tags": "escaping" }
is MariaDB error related to Automatically add new top-level pages I ran some checks on RAM on my machine and discovered this error "Error: (06/14/2020 12:45:54 PM) (Source: MariaDB) (User: ) Description: mysqld.exe: Table '.\test\wp_usermeta' is marked as crashed and should be repaired" I have local WP install on localhost. Does this error somehow impact the fact that I am unable to stop auto add of new pages to primary menu even if I have 'Automatically add new top-level pages to this menu' unchecked? EDITS: **function.php child theme** function archive_menu() { register_nav_menu('archive_menu',__( 'Archive' )); } add_action( 'init', 'archive_menu' ); **index.php child theme** <?php wp_nav_menu( array ( 'theme_location'=> 'archive_menu') );?>
I can't see how, because the `wp_usermeta` table contains the metadata about your users. The menu items are stored in the `wp_posts` table, and the menu options (including the status of the "Automatically add new top-level pages") is stored in `wp_options`. I would definitely recommend that you repair the crashed table, though, because it's likely having an impact on your WordPress site. See this question and its answers for advice. **Edit** Your posted code looks right to me, and if you've assigned the menu properly then it should be working. I'm not sure what the problem might be. Does the menu work properly in a default theme?
stackexchange-wordpress
{ "answer_score": 0, "question_score": 0, "tags": "menus, database" }
How to programatically toggle the media setting "Organize my uploads into month- and year-based folders"? How can I programmatically change this setting? ![admin settings page](
The (database) option name for that setting is `uploads_use_yearmonth_folders`, so you can use `update_option()` to programmatically change the setting's value: // 1 to enable the "checked" state update_option( 'uploads_use_yearmonth_folders', 1 ); You can also use a filter hook such as `option_<name>`: add_filter( 'option_uploads_use_yearmonth_folders', function ( $value ) { return 1; // 1 = checked } ); Or am I not understanding the question? :)
stackexchange-wordpress
{ "answer_score": 1, "question_score": 0, "tags": "media" }
Get current user data I do work on filter posts by current user, but in my dropdown list, i can get only all users list, but I need to see only the current user function getСurrentUserForFilter(){ $res = ''; $user_query = new WP_User_Query(array('number'=>999)); $users = $user_query->get_results(); foreach($users as $user){ echo'<option value="'.$user->ID.'">'.$user->user_email.'</option>'; } return $res; } what am I doing wrong?
If you just want to write a single `<option>` for the current user, you can get the user object from wp_get_current_user() \- you don't need a WP_User_Query at all: function getСurrentUserForFilter() { if ( is_user_logged_in() ) { $user = wp_get_current_user(); echo '<option value="'.$user->ID.'">'.esc_html($user->user_email).'</option>'; } }
stackexchange-wordpress
{ "answer_score": 2, "question_score": 0, "tags": "filters, users" }
Which things should be called with `after_setup_theme`? I just read about the existence of `after_setup_theme` in this blog post. I'm not experienced in Wordpress development, so I was wondering if there exists some kind of list with all the things that should be in called with `after_setup_theme`? I can't find good documentation about it, so can you also explain something about the function itself and what the best way is to use it?
`after_setup_theme` is a wordpress hook which fires after the theme is loaded after_setup_theme runs before init and is generally used to initialize theme settings/options before a user is authenticated. According to the Codex: This is the first action hook available to themes, triggered immediately after the active theme's functions.
stackexchange-wordpress
{ "answer_score": 0, "question_score": 0, "tags": "hooks" }
Setting 'autoload' to 'no' with Settings API I've looked at the Settings API codex page, < and I can't find anything related to setting `autoload` to `no` for any options using the Settings API. Is there any way to achieve this using the Setttings API? Asking because I have many DB table `options` entries that were created using `register_setting` and all of the `options` have `autoload` set to `yes`. I need to optimize this because hundreds of entries are being loaded on every page load unecessarily.
The only way to accomplish this is to add the option to the database yourself before the Settings API does so. To do this, add a 'sanitize_callback' to the register_settings function: `register_setting ('my_options', 'my_option_name', array ('type' => 'string', 'sanitize_callback' => 'my_function_name'));` Then, in your function, update the option yourself: function my_function_name ($value) { update_option ('my_option_name', $value, false); return $value; } `
stackexchange-wordpress
{ "answer_score": 2, "question_score": 3, "tags": "options, settings api" }
How to remove author name and link from a shared link preview? I have a weird problem with a wordpress site I'm working on, when we share links for it on discord shared link contains my login name and a link to author posts page (index is a page not a blog page) but when I look at the source there is not a single reference to my login name on the page, also facebook and other social media sites don't have this as there is no metadata about it but somehow discord fetches my username (probably because I'm the creator of it) but I'm unable to find how it does that and remove that from links. Any ideas? Page in question: angelicthegame.com/ Discord link preview: ![Discord link preview with author name]( Erdi is the author name displayed and links to <
This might help you. Add this script to functions.php. It will unset author from oembed preview. Remember Discord might already cached your URL. You may not get immediate result. add_filter( 'oembed_response_data', 'disable_embeds_filter_oembed_response_data_' ); function disable_embeds_filter_oembed_response_data_( $data ) { unset($data['author_url']); unset($data['author_name']); return $data; } for more explanation head over here
stackexchange-wordpress
{ "answer_score": 4, "question_score": 2, "tags": "links, previews" }
Want to filter only parent post in admin area ![enter image description here]( I want a filter like this in my custom post "books". This filter should only bring up the parent post.
In addition to my previous answer add following code. It should work fine add_filter( 'views_edit-books', 'add_filter_link' ); function add_filter_link( array $views ) { $url = add_query_arg( array('bfilter'=>'parents','post_parent'=>0,'post_type'=>'books'), 'edit.php' ); $views[ 'post_parent' ] = sprintf( '<a href="%1$s"%2$s>%3$s</a>', esc_url( $url ), ( is_filter_active() ) ? ' class="current" aria-current="page"' : '', 'Post Parents' ); return $views; } function is_filter_active() { return (filter_input( INPUT_GET, 'bfilter' ) ==='parents'); } if you already not used bellow code then add that too function make_post_parent_public_qv() { global $pagenow; if ( is_admin() && $pagenow == 'edit.php' ) $GLOBALS['wp']->add_query_var( 'post_parent' ); } add_action( 'init', 'make_post_parent_public_qv' );
stackexchange-wordpress
{ "answer_score": 0, "question_score": 0, "tags": "custom post types, wp query, custom taxonomy, filters, wpdb" }
Add a div of content within the_content after a certain block In gutenberg I have several blocks: paragraph heading paragraph code paragraph In php I'd like to find the `code` block and append content after the block. I'd imagine I need to use `add_filter` and `the_content`, but I'm not sure how to go about it after that.
Yes, `add_filter()` is what you're looking for, but to identify a specific block, you want the `render_block` hook. <?php add_filter('render_block', function($block_content, $block) { // Only for Core Code blocks if('core/code' === $block['blockName']) { // Add your custom HTML after the block $block_content = $block_content . '<div>Test addition</div>'; } // Always return the content return $block_content; }, 10, 2); ?> Anywhere the code block is rendered (which would currently be the front end of a Page, Post, or CPT, but in the future could be elsewhere) your added code will appear.
stackexchange-wordpress
{ "answer_score": 5, "question_score": 0, "tags": "filters, the content" }
How to get the revisions feature back on the classic editor? Any of the recent Wordpress updates have removed the revision option from the classic editor. It runs in the background and saves the regions but no way to access it on the classic editor. Gutenburg has and supports the revision option well. But I don't use Gutenburg. I don't know when they removed the feature, but I only realized today. How can I get the feature back on my Classic editor? I checked my database, I have the revisions, even for new posts, and I also checked by enabling the Block editor. ![](
I used to disable the Gutenberg with this: //disable gutenburg add_filter('use_block_editor_for_post', '__return_false', 10); This filter disables the Gutenberg sitewide but it doesn't work smoothly in other custom-post-types. Not only the revisions but other features are also hidden on the post edit screen of custom-post-types. Changing this to the post type filter works smoothly across all post types. //disable Gutenburg add_filter( 'use_block_editor_for_post_type', '__return_false', 10 );
stackexchange-wordpress
{ "answer_score": 0, "question_score": 0, "tags": "block editor, revisions" }
WordPress Theme With Modified View I'm very new to WordPress. I'm going through some tutorials in developing a theme. What I'm trying to grasp is creating a theme when the pages are a bit different. They all have the same theme but the layout is different for example on the home page and the rest of the pages. For an example of a home page: ![enter image description here]( And for all the content pages the look is somewhat different: ![enter image description here]( I'm looking at the hierarchy and I see home.php and page.php, but I'm not 100% sure how they tie in. Any advice or links to better understand how this works would be appreciated
Sometimes the names can be misleading as home.php actually refers to the page that stores all of your blog posts. In general, use either page-home.php or front-page.php for the home page and then page.php for the rest. Whenever you have a specific page with a different layout, you can create a new template that is styled specifically for that. Eg. page-contact for a contact page that doesn't follow the styles of other pages. The page-XXXXX.php is dependent on the slug of the page so that is how WordPress finds it.
stackexchange-wordpress
{ "answer_score": 1, "question_score": 0, "tags": "theme development" }
Hide author info in single posts by certain users I use this code to add custom CSS if single post and in certain categories: function hide_author() { global $post; if (is_single($post->ID) && in_category(array( 'category 1', 'Category 2'), $post->ID)) { ?> <style type="text/css"> .author-info {display: none;} </style> <?php } } add_action('wp_head', 'hide_author'); I was wondering how to fire wp_head action if single post by certain users (either by user ID or username)? Can I use wp_set_current_user ()? if so, how to use it exactly? Thanks,
No, there's no need to use `wp_set_current_user()`. > I was wondering how to fire `wp_head` action if single post by certain users (either by user ID or username)? You can use `$post->post_author` to get the ID of the author of the post, and put the user ID list in an array, then just do `in_array()` to check if the author ID is in the ID list. For example: function hide_author() { //global $post; // Instead of this, $post = get_post(); // I would use this one. // Define the user ID list. $user_ids = array( 1, 2, 3 ); if ( $post && is_single( $post->ID ) && in_array( $post->post_author, $user_ids ) ) { ?> Your code here. <?php } } And that example would run only on single post pages and that the current post's author ID is in the `$user_ids` list/array.
stackexchange-wordpress
{ "answer_score": 0, "question_score": 0, "tags": "functions, customization, wp head" }
Put post ID on the custom post type URL I want to get this link structure mysite.com/sa/post-slug/post_id/ on my custom post-type. This is the post_type: // ex_article Post type add_action( 'init', 'ex_article_init' ); function ex_article_init() { $args = array( 'labels' => array( 'name' => _x( 'Article', 'Post type general name', 'textdomain' ), 'menu_name' => _x( 'Ex Article', 'Admin Menu text', 'textdomain' ) ), 'public' => true, 'show_ui' => true, 'hierarchical' => false, 'rewrite' => array('slug' => 'sa', 'with_front'=>false ), --- --- --- ); register_post_type( 'ex_article', $args ); } On permalink setting, I use `Post Name : mysite.com/sample-post/`. Using a custom structure is not an option for me, I need to avoid it, and also it does nothing to custom post type.
It's quite easy, actually: 1. Change the generated permalink structure so that it ends with the post ID and not the post slug (but it still contains the post slug): // After you registered the post type: register_post_type( 'ex_article', $args ); // .. run this code: global $wp_rewrite; $wp_rewrite->extra_permastructs['ex_article']['struct'] = 'sa/%ex_article%/%post_id%'; 2. Then replace the post ID placeholder (`%post_id%`) in the generated permalink URL with the correct post ID: add_filter( 'post_type_link', function ( $post_link, $post ) { if ( $post && 'ex_article' === $post->post_type ) { return str_replace( '%post_id%', $post->ID, $post_link ); } return $post_link; }, 10, 2 ); And don't forget to **flush/regenerate the rewrite rules**! Just visit the permalink settings page without having to click on the "save" button.
stackexchange-wordpress
{ "answer_score": 5, "question_score": 2, "tags": "permalinks, url rewriting" }
Wordpress 403 error on form submission with Ajax I have a wordpress multisite set up, and in my sub-site (called "team" site) I have buddypress. There is an activity stream, but I cannot post updates to the activity because there is a 403 error. When I click "submit" on a post and inspect the error, this is what I see on the network tab: Request URL: Request Method: POST Status Code: 403 Remote Address: <<masked by me>>.31.79.150:443 Referrer Policy: no-referrer-when-downgrade And when I check the actual response tab, this is the message: The link you followed has expired. Please try again. What could be causing this problem? I cannot replicate this error on my local host.
the issue was to do with cookies. In a multi-site setup, the cookies that are set upon user login depends on which subsite the user logged in from; not all cookies give equal authority to submit forms. so the solution is either you (a) change your cookie domain to one common one in wp_config.php - in which case a user can log in anywhere and the cookies will be fine, or (b) have a redirect so that there is only one site that users can log in from. Because of my unique setup, I opted for (b)
stackexchange-wordpress
{ "answer_score": 0, "question_score": 0, "tags": "ajax, errors" }
Enqueue plugin for specific pages I want to enqueue my plugin for certain pages. I've tried several things but nothing worked so far: add_action( 'init', 'my_enqueue' ); function my_enqueue() { global $post; if( $post->ID == 380 || is_home() || is_front_page() || is_single(380) || is_page(380)) { wp_enqueue_script( 'lister_js', plugins_url( '/js/lister.js', __FILE__ ), array('jquery'), filemtime( '/js/lister.js', __FILE__ )); wp_localize_script( 'lister_js', 'my_ajax_object', array( 'ajax_url' => admin_url( 'admin-ajax.php' ) ) ); } } The post id is 380 according to the db. I even checked the url and it is ".../wp-admin/post.php?post=380&action=edit". So I'm pretty sure the id is correct.
It started to work once i change add_action( 'init', 'my_enqueue' ); to add_action( 'wp_enqueue_scripts', 'my_enqueue' );
stackexchange-wordpress
{ "answer_score": 0, "question_score": 0, "tags": "plugins, wp enqueue script" }
Design with Elementor and code the rest? Do you guys know if it is possible to design a website using Elementor or any other editor and then coding the rest using my custom PHP code? I tried to use a theme downloaded from the internet and when I started editing with Elementor the design does not reflect on theme files, hence I cannot add code to the website. I am asking this as I think designing the website will take a lot of time for that purpose I want to use a theme from the internet and edit using Elementor then add my custom code...
It is not possible to use a drag and drop page builder like Elementor to edit the design of a custom-coded theme. If you really want to use Elementor, you could use Elementor Pro's theme builder to recreate the original theme manually.
stackexchange-wordpress
{ "answer_score": 1, "question_score": 0, "tags": "php, themes" }
Blog page and the Home page showing the same content I am trying to set up a website with askme as the main template and consider myself as someone who dosent knows website coding yet.And so I am using Wordpress to build a website.But the only problem I am facing is that my blog and home page are showing the same contents that of home page.I want the home page to be showing the summary questions of my website, which it is doing but my blog page instead of showing all the post it is also showing the questions.In the settings on the reading tab I have put homepage as "home" and posts page as "blog" what else should I do
at the begining in wordpress dashboard ( panel) go to pages and create 2 pages, one 'home', and another 'posts'. After navigate in admin panel to settings section and select 'reading' option which looks =>![enter image description here]( From there select your freshly created pages for each purpose, you can edit content of pages in admin dashboard => pages section , you should have now fully working two different pages for each purpose.
stackexchange-wordpress
{ "answer_score": 0, "question_score": 0, "tags": "css, homepage, blog page" }
Can you Recover a Wordpress User from a Backup so basically i deleted a wordpress user, and with that user, the settings, media and many pages were deleted. is there a way to restore only that user, because he has been inactive for about a year, and the last backup is about one year ago.
I just did a test on Wordpress 5.4.2. I made a new user, and then made a post and a page from that user, then deleted the user and chose not to reassign content to another user. I looked in the database and found that the data in wp_users for the user was completely deleted, but in wp_posts the content created by that user was still there but set to trashed. So, you may find that you can recover the posts/pages from the trash, however if they've been deleted from the trash they might be gone permanently. You can always recover data from backups manually, however it would be quite a manual process to find the data from the backup and re-inserting it into the database manually, or re-entering it through the WP dashboard. For more help see if you have a database backup that you can look at in a text editor and search for your wp_posts table to see if you can find where that information is, and paste an example of it here.
stackexchange-wordpress
{ "answer_score": 0, "question_score": 0, "tags": "users, backup" }
How can I get user data into a javascript object? I have the code below in my functions.php file. However, when I try to access the variable `theUser` in my `custom.js` file it comes back as `undefined`. Functions.php: function theme_scripts() { global $current_user; $current_user = wp_get_current_user(); wp_enqueue_script( 'theme-script', get_stylesheet_directory_uri() . '/assets/js/custom.js', array( 'jquery' ), '', true ); wp_localize_script( 'theme-script', 'theUser', array ( 'username' => $current_user, ) ); } add_action( 'wp_enqueue_scripts', 'theme_scripts' ); Custom.js: var theUser; var userName = theUser.username.data.display_name; var userEmail = theUser.username.data.user_email; console.log(theUser);
that's because you have defined the variable `theUser` as null and overridden the one that has the object before then you have tried to call the object. just remove this line `var theUser;`
stackexchange-wordpress
{ "answer_score": 1, "question_score": 0, "tags": "javascript, wp localize script" }
Upgrading PHP version results in "Use of undefined constant WP_CONTENT_DIR" warning? On my HostGator shared hosting with a CPanel option to set PHP per domain, if I turn on PHP 7.3 (or other 7.x versions) for my existing blog I get an error page: > Warning: Use of undefined constant WP_CONTENT_DIR – assumed ‘WP_CONTENT_DIR’ (this will throw an Error in a future version of PHP) in /my_site/public_html/wp-includes/load.php on line 141 Your PHP installation appears to be missing the MySQL extension which is required by WordPress If I Google this, all the advice is about how to install `mysqld`, but it's surely already installed as doing a fresh install of WordPress on a separate sub-domain works perfectly under PHP 7.3, so I must be missing something in my older site's WordPress `wp-config.php`, perhaps. Looking at working and failing versions, though, I cannot see an obvious difference.
Here's what worked for me: My Hostgator WordPress site was throwing the same error until I commented out the top-level `.htaccess` file. Like so: ![I commented out the PHP default settings]( My website is a subdomain, so it had it's own `.htaccess`, so that's where the php version was specified (cpanel did this automatically). I didn't have to edit `wp-config.php` or anything else. In the comments of this post is where I found this solution: <
stackexchange-wordpress
{ "answer_score": 3, "question_score": 5, "tags": "php, errors, wp config" }
Registration roles I stumbled on a Problem recently: I have a Registration Form on my Website which gives the role "Subscriber" by default to everybody who tries to register, but I want a specific E-Mail Domain to get a different role. I found a WPSE question about this but I don't know where I should insert the PHP Code? `functions.php` in my Themes folder? I would be really thankful if someone with more knowledge could help me. I'm using WordPress 5.4.2 with WooCommerce and the Theme Shop-Isle
Yes, add the code in functions.php file of the activated theme.
stackexchange-wordpress
{ "answer_score": 0, "question_score": 0, "tags": "woocommerce offtopic, user registration" }
Removing menus from users other than the administrator I want to remove some of the menu links from all users except the administrator. How can I do it?
I found the code I was looking for, thank you. add_action( 'admin_init', 'my_remove_menu_pages' ); function my_remove_menu_pages() { global $user_ID; if ( current_user_can( 'author' ) ) { remove_menu_page( 'tools.php' ); remove_menu_page( 'edit-comments.php' ); remove_menu_page( 'wpcf7' ); remove_menu_page( 'upload.php' ); remove_menu_page( 'index.php' ); } }
stackexchange-wordpress
{ "answer_score": 0, "question_score": 0, "tags": "filters, user roles, admin menu, dashboard, wp link pages" }
Wordpress theme options checkbox default checked state I am developing a custom theme. I added a checkbox with the settings api. They all work except for the ones that are checked by default (checked="checked"). They do not save when they get unchecked (state only, value does save). Now, there are two things I'd like to be able to do: 1 - save the checkbox state when unchecked on default checked checkboxes. 2 - save default checked checkboxes automatically without the user first having to click "Save changes". (so on page load save default checked checkboxes for example). **I searched everywhere for an answer already but I could not find anyone with this same question. They all handle checkboxes but none handle default "checked" checkboxes.** The code for the checkboxes: echo '<input type="checkbox" class="theme-custom-checkbox" name="theme_custom_option" value="1" checked="checked"' . checked( 1, get_option( 'theme_custom_option' ), false ) . ' />';
With the code that you've added to your question, you're adding the HTML 'checked' attribute twice, which is probably why things are getting confused. You have it hard-coded as `checked="checked"`, but then `checked( 1, get_option( 'theme_custom_option' ), false )` will write another checked attribute corresponding to the actual value of the option. You should be able to verify this would have been able to debug it by looking at the generated HTML with view-source or developer tools. Taken from the docs page for the `checked` function in Wordpress < your code should probably look something like this: echo '<input type="checkbox" class="theme-custom-checkbox" name="theme_custom_option" value="1" ' ; echo checked( 1, get_option( 'theme_custom_option' ), false ); echo ' />'; Note code tidied a bit for readability
stackexchange-wordpress
{ "answer_score": 0, "question_score": 0, "tags": "theme development, themes, settings api" }
How to get users by specific ID's WordPress How to get users by specific users ID's in WordPress. $args = array( 'number' => -1, 'fields' => array( 'ID', 'user_email', 'display_name', 'user_url' ) ); $users = get_users( $args);
To get a list of users by their IDs you simply need to add the `include` argument to your query; $args [ 'include' => [ 1, 2, 3, 4 ], // Get users of these IDs. 'fields' => [ 'ID', 'user_email', 'display_name', 'user_url' ], ]; $users = get_users( $args ); You don't need to use the `number` argument as you're already limiting your result by the amount of IDs provided in `include`. See this page for more info on the available arguments. You could also use the `WP_User_Query` class to retrieve them; $args [ 'include' => [ 1, 2, 3, 4 ], // Get users of these IDs. 'fields' => [ 'ID', 'user_email', 'display_name', 'user_url' ], ]; $user_search = new WP_User_Query( $args ); $users = $user_search->get_results();
stackexchange-wordpress
{ "answer_score": 1, "question_score": 0, "tags": "users" }
Remove slashes (both before and after) in relative post url I've seen a few " _remove last_ " slash, but not how to remove both the first and last slash. I've tried: $post_url_rel = wp_make_link_relative(get_permalink( $post_id )); ltrim($post_url_rel, '/'); rtrim($post_url_rel, '/'); But it still says _/postname/_ Anybody has any idea why this didn't work?
It's because you're not actually putting the result of `ltrim()` and `rtrim()` back into the variable. Those functions _return_ the trimmed value, they don't modify the passed variable. So you need to do this: $post_url_rel = wp_make_link_relative(get_permalink( $post_id )); $post_url_rel = ltrim($post_url_rel, '/'); $post_url_rel = rtrim($post_url_rel, '/'); Or better yet, just use `trim()`, which will remove it from both ends: $post_url_rel = wp_make_link_relative(get_permalink( $post_id )); $post_url_rel = trim($post_url_rel, '/');
stackexchange-wordpress
{ "answer_score": 2, "question_score": 1, "tags": "posts, customization, urls" }
How to get category URL with the slug? I have a variable that contains the slug of a category. With that slug I want to create a link to the archive page that displays all the posts in that specific category. What is the best or fastest way to go from slug to category URL? Preferably I don't want to use a lot of variables (like when going from slug > id > url, each with a different variable). I would like a function that does one of the following, to keep the file as clean as possible. `echo get_url_function(slug)` or `echo get_url_function( get_id_function (slug) )` Thanks a lot in advance!
The WP function `get_category_link()` will do the trick. /** * Gets the URL for a category term archive based on the category's slug. * * @param string $category_slug The slug of the category to get the category arcive for. * * @return string The category (term) archive URL. Empty string on error. */ function wpse_get_category_url_by_slug( $category_slug ) { return get_category_link( get_cat_ID( $category_slug ) ); } Instead of a creating a wrapper like the example above, you could also just call the WP function directly: `get_category_link( get_cat_ID( $category_slug ) )`
stackexchange-wordpress
{ "answer_score": 2, "question_score": 1, "tags": "categories, permalinks, taxonomy, id, link category" }
Working with a WP Starter theme I am building a custom theme and I am starting with a starter theme. When add my CSS, do I modify the CSS in the style.css or add my own CSS on top of what's already there? I don't want to remove something that is needed.
This is a bit subjective, but with a starter theme I'd go ahead and overwrite the existing styles as you see fit. You can always reference the original copy if you're worried about breaking something. By _starter theme_ , I mean a theme that has a bunch of boilerplate is intended to by copied and modified/added to (_s, for example).
stackexchange-wordpress
{ "answer_score": 0, "question_score": 1, "tags": "theme development" }
how to disable Yoast SEO schema from homepage only? I know it can be disabled everywhere with add_filter( 'wpseo_json_ld_output', '__return_false' ); But i want to keep the breadcrumbs so if i could do that only `if (is_home())` that would be perfect. I just don't know where to hook it.
try like this function filter_wpseo_json_ld_output( $bool, $context ) { if(is_home()){ return false; } return $bool; }; // add the filter add_filter( 'wpseo_json_ld_output', 'filter_wpseo_json_ld_output', 10, 2 );
stackexchange-wordpress
{ "answer_score": 1, "question_score": 0, "tags": "plugin wp seo yoast" }
location lock wordpress website Hi I am setting up a WordPress website for a venue. I need to lock the latitude and longitude of the venue so that the website only open inside the venue, i tried setting it up on local host to only open with the Wifi but most of the customers use their 4G. any help would be appriciated! Thanks
There are open/free APIs that allow geolocation based on the IP address. IP address of a mobile should be geo-correct. I use this site, with a CURL function to return the Geo information. Go to the URL in the code to get details on the return values. function grabIpInfo($ip) { //$ip = '185.164.57.189'; // france //$ip = '110.33.122.75'; // australia $curl = curl_init(); curl_setopt($curl, CURLOPT_URL, " . $ip); curl_setopt($curl, CURLOPT_RETURNTRANSFER, TRUE); $returnData = curl_exec($curl); curl_close($curl); return $returnData; } You'll need to pass the IP address, which is available with $_SERVER["REMOTE_ADDR"] That might get you started on the code you need. And testing (I hard coded some other-country IP addresses for my testing, as shown in the code).
stackexchange-wordpress
{ "answer_score": 0, "question_score": 0, "tags": "plugins, php" }
$_POST field value gets altered after "init" I'm new to wordpress development. I'm trying to develop a simple plugin for practice. It involves a form submission from the frontend. The form has an input with the following code. <input type='hidden' name='test' value='{"id": 1}'/> When I submit the form, the value of 'test' field gets altered after the "init" hook. My plugin code looks like the following add_action('init', [$this, 'init']); function init() { printe_r($_POST); } **Output:** Array ( [test] => {\"id\":1} ) The problem is that **json_decode** errors out. I have to use **stripslashes** like below to decode the json string. json_decode(stripslashes($_POST['test'])); Is this behavior expected in Wordpress?
Yes, it's the expected behaviour. There's information on why it works like this here, and this function which can help in removing slashes from larger data structures: < In the short term, if you can live without JSON for this field, why not just remove it, and if you need multiple hidden fields add them separately, e.g.: <input type='hidden' name='testId' value='1'/> <input type='hidden' name='otherId' value='123'/> And you can get those directly with: echo $_POST['testId']; echo $_POST['otherId']; Will output: 1 123
stackexchange-wordpress
{ "answer_score": 0, "question_score": 0, "tags": "plugins, input" }
Warning: printf(): Too few arguments in helpers.php file So I'm getting the following error `Warning: printf(): Too few arguments in /lib/helpers.php on line 34` So line 34 is `'class' => []` // Define the read more url function read_more_url() { // Grab the posts link and title echo '<a href="' . esc_url(get_the_permalink()) . '" title="' . the_title_attribute(['echo' => false]) . '">'; printf( // Filters text content and strips out disallowed HTML wp_kses( __('Read more <span class="u-screen-reader-text">about %s</span>', 'Sema'), [ 'span' => [ 'class' => [] ] ] ) ); } Could someone tell me what I might be doing wrong? The echo is working correctly.
Your `printf` statement awaits additional string argument which would be substituted instead of `%s`: printf( // Filters text content and strips out disallowed HTML wp_kses( __('Read more <span class="u-screen-reader-text">about %s</span>', 'Sema'), [ 'span' => [ 'class' => [] ] ] ), "some subject" ); This example would produce the following output: `Read more <span class="u-screen-reader-text">about some subject</span>`
stackexchange-wordpress
{ "answer_score": 1, "question_score": 0, "tags": "php, theme development, themes, child theme" }
How to add CSS class to <li> and <a> and id in a nav menu with code? I have registered nav menu. here is the code <?php wp_nav_menu( array ( 'theme_location' => 'top-menu', 'menu_id' => 'navbarSupportedContent', 'menu_class' => 'navbar-nav ml-auto', 'container' => 'ul', ) ); ?> but `<li>` and `<a>` have classes that are not applied to the nav menu wordpress code. so how to add them? <li id="f-one" class="nav-item"><a class="nav-link" href="#home">Home</a></li> so any of f-one id or nav-item, nav-link added to the wordpress nav menu style. how to add them please?
thank you. I just have changed the theme after reseting. that was the problem and it is solved now and the style is as it is.
stackexchange-wordpress
{ "answer_score": 0, "question_score": 0, "tags": "menus, css" }
How to search for many post types? I actually wanted to reply to another post, unfortunately that is no longer possible. Therefore a short and crisp question. ;-) If I want to search in several post types, can I simply work with `'post_type' => 'post'` with comma values? `'post_type' => 'post', 'Pages', 'etc ..'`
This is documented here: < So to search for several post types you do: $args = array( 'post_type' => array( 'post', 'page', 'movie', 'book' ) ); $query = new WP_Query( $args );
stackexchange-wordpress
{ "answer_score": 3, "question_score": 1, "tags": "custom post types" }
See if a post has a specified tag I'm trying to see if a post (thru id) has a specified tag if has_tag( $tag = 'Cat', $post = $post_id ) { $taganimal = "Cat"; } I tried this, but it just crashes the site . Got idea from < but can't get it to work..
You should wrap your condition with brackets according to PHP syntax: if (has_tag('Cat', $post_id)) { $taganimal = "Cat"; } If you need to check multiple tags you can use something like foreach (['Cat', 'Dog'] as $animal) if (has_tag($animal, $post_id)) { $taganimal = $animal; break; } but it would find only the first tag listed in array in case the post has several of them.
stackexchange-wordpress
{ "answer_score": 1, "question_score": 0, "tags": "posts, search, tags" }
Check with Jquery if second level checkbox from categories are checked I have a two level list of Categories. First levels are multiple (more than 30). Also the associated child are a lot From the WP-admin, I would like to check whenever at least one of the second level (child) checkboxes are checked. I will run the jquery function after the #post has been submitted. That part is easy, but how to check if any of the childs have been checked is impossible for me to figure out. Banging my head already for days :)
Try this selector: if ($('div#category-all ul.children input:checked').length) { // at least one of the child categories is selected }
stackexchange-wordpress
{ "answer_score": 0, "question_score": 0, "tags": "categories, wp admin" }
Are there any know limitations on the date field, especially how old dates can be? Our site needs a way to order a large number of posts (think +6000). After looking at some plugins I have decided to just use the date field since it is built into wordpress. It's kind of silly, but it will meet our need and hopefully be compatible with any future iterations of the WordPress software or plugins. _**Is there a limit to how far back in time posts can be dated?**_ We shouldn't have to go so far back, but I just wanted to check if anyone knew.
Almost every PHP date/time function is dealing with the UNIX epoch timestamp, which starts from 00:00:00 UTC on 1 January 1970. So I strongly encourage you not to use dates before 01.01.1970 to avoid incompatibilities with the most of PHP code used by third party plugins.
stackexchange-wordpress
{ "answer_score": 1, "question_score": 0, "tags": "date" }
How to show address in one row? By using contact form 7 i created address page. By selecting the city they can view the list of branches in that particular city but here i am getting small problem in first row address are not coming properly. For reference please find the attached image and url < ![enter image description here]( Thanks SomuN
It has to do with your `<br>` between each label field. Its not a PHP problem its a CSS. Try to add .wpcf7cf_group br { display: none; } to your css file or use a wordpress plugin like Simple Custom CSS.
stackexchange-wordpress
{ "answer_score": 0, "question_score": 0, "tags": "css" }
How to view all currently registered block patterns? I've registered a block pattern in my custom theme (using register_block_pattern) and it's not displaying in the block patterns list so I'm trying to debug whether I registered it properly. How could I programmatically find currently registered block patterns?
This looks like quite new functionality, the docs say 'experimental' and the first commit of this code to the WP repo was 6 days ago from date of this writing, so wouldn't be surprised if you'll have issues with what you're doing related to it being in development. The class that manages block patterns is easy to read: < So you could call e.g. the `get_all_registered()` method like: `WP_Block_Patterns_Registry::get_instance()->get_all_registered()` or e.g. check if your pattern is registered: `WP_Block_Patterns_Registry::get_instance()->is_registered("your_pattern_name")` I'd suggest if you're having problems you might either want to wait until it's a more stable feature or contact the people working on it (e.g. you could start by contacting the person who made that commit as it looks like they're actively working on it) HTH!
stackexchange-wordpress
{ "answer_score": 1, "question_score": 0, "tags": "block editor" }
Upload file on pre_update_option_{option_name} is there a way to upload a file while saving options in WP ? I have this option setting (save is binded to options.php) and need to upload and store a file on server ![enter image description here]( and cannot find the file in update_option_{option_name}: add_action('init', array($this,'upload_credentials'), 10); function upload_credentials( ) { //CRM_adv_settings is the option name add_filter( 'pre_update_option_CRM_adv_settings', array($this,'system_save_file'), 10, 2 ); } function system_save_file($new_value, $old_value){ //$rawData = file_get_contents("php://input"); $f=$_FILES; $p=$_POST; } Cannot find $_FILES, in $_POST there's the filename; tried several variation about `update_option` and `pre_update_option` but no success, any idea?
I'm quite sure the problem is **not** with the WordPress hook you're using. Instead, the following: > Cannot find `$_FILES`, in `$_POST`, there's the filename .. is most likely because your form tag (`<form>`) does not have the required `enctype` attribute which must be set to `multipart/form-data` to make file upload input works in that the file gets uploaded to the server — without setting the `enctype` to `multipart/form-data`, the input still works (i.e. you can select a file that you want to upload), but it'll work like a standard input field where the browser submits only the file name (e.g. `my-image.png`) and not the actual file itself (which PHP puts in the `$_FILES`). So make sure your form tag has the attribute `enctype="multipart/form-data"`: <form method="post" action="options.php" enctype="multipart/form-data"> ... </form>
stackexchange-wordpress
{ "answer_score": 1, "question_score": 0, "tags": "options" }
Is it possible to checkout with 2 different shipping options on a single order? This is regarding a marketplace in WooCommerce that has different vendors. Let's say you are buying item A from Vendor 1 and item B from Vendor 2. And you would like to get the first item shipped to your home, but you want to pick up Item B, since it's close to your home. Is it possible to checkout on a single order choosing a shipping method for item A and a different one for item B? Thanks!
Normally I would suggest doing this programmatically, but honestly try this plugin If you want to go the code route checkout this article
stackexchange-wordpress
{ "answer_score": 1, "question_score": 0, "tags": "woocommerce offtopic" }
Hide specific category from wp_list_categories I have to hide 3 categories from the list, at the moment to view the list I use this function function genres() { $args = array('hide_empty' => true, 'title_li'=> __( '' ), 'show_count'=> 0, 'echo' => 0 ); $links = wp_list_categories($args); $links = str_replace('</a> (', '</a>', $links); $links = str_replace(')', '', $links); echo $links; } <?php genres(); ?> i need to hide category id 1 and 2
You can use the `exclude` parameter: > **'exclude'** > _(array|string)_ Array or comma/space-separated string of term IDs to exclude. If `$hierarchical` is true, descendants of `$exclude` terms will also be excluded; see `$exclude_tree`. See `get_terms()`. So with your `$args`: $args = array( 'hide_empty' => true, 'title_li' => '', 'show_count' => 0, 'echo' => 0, // Excludes specific categories by ID. 'exclude' => array( 1, 2 ), );
stackexchange-wordpress
{ "answer_score": 1, "question_score": 0, "tags": "categories, list" }