INSTRUCTION
stringlengths
11
999
RESPONSE
stringlengths
0
999
SOURCE
stringlengths
16
38
METADATA
dict
Is it best practice to use English as the base of a translation-ready theme? If I make a theme and add hard-coded text using `_e()`, `__()`, `esc_attr()` and so on. Could I do this in polish (or whichever language) and then add English translation po/mo files with the other languages I want to include or is this backwards and bad practice?
The default language of WordPress is always English (`en-US`). Regardless of what your site language is set to. This is what the entire WordPress community expects for the language of source strings, and how many translation projects for WordPress will be set up too. So yes, it **is bad practice** to choose use different source language from the system you're writing for. You could choose to ignore best practice, but with Polish you will run into a technical problem too. WordPress has a built-in limitation that you can only define two source forms of a pluralized string. This is actually a limitation of the gettext system, which is biased towards English. In their own words: "the coding standards for the GNU project require program being written in English". You could say the same of WordPress.
stackexchange-wordpress
{ "answer_score": 1, "question_score": 0, "tags": "translation" }
How does WordPress differentiate what scripts are loaded in wp_head() and wp_footer()? A newbie question. I have gone through the `wp_head()` and `wp_footer()` documentation and both are said to be including the scripts and styles. So my question is how does WordPress differentiate which scripts need to be in the `wp_head()` and which needs to be in `wp_footer()`. My understanding is that the `wp_head()` will include all the scripts and styles in the header section of the webpage, and calling the `wp_footer()` will again include the same scripts and styles in the footer section of the website. I know it is wrong.
wp_enqueue_scripts has a parameter which specifies if the script should be rendered in `wp_head` or `wp_footer` The function signature is this: wp_enqueue_script( string $handle, string $src = '', array $deps = array(), string|bool|null $ver = false, bool $in_footer = false ) Note that it is the **5th** parameter, so if you wish to not have any dependencies and use the default version number for your script you still have to supply those parameters. For example: wp_enqueue_script( 'your_script_name', 'your_script_location', array(),false, true ); ^ // This will cause the script to render in wp_footer |
stackexchange-wordpress
{ "answer_score": 2, "question_score": 0, "tags": "php" }
Custom post registration causing errors I copied this code from a youtuber. It works for him, but not for me. Does the code contain any errors? As soon as I put it in, my WordPress breaks and won’t load. function gt_custom_post_type() { register_post_type('project', array( 'rewrite' => array('slug' => 'projects'), 'labels' => array( 'name' => 'Projects' 'singular_name' => 'Project', 'add_new_item' => 'Add New Project', 'edit_item' => 'Edit Project' ), 'menu-icon' => 'dashicons-media-document', 'public' => true, 'has_archive' => true, 'supports' => array( 'title', 'thumnail', 'editor', 'excerpt', 'comments' ) ) ); } add_action('init', 'gt_custom_post_type');
There are many small problems with this code (see my comments below): function gt_custom_post_type() { register_post_type('project', array( 'rewrite' => array('slug' => 'projects'), 'labels' => array( 'name' => 'Projects', // <- missing comma 'singular_name' => 'Project', 'add_new_item' => 'Add New Project', 'edit_item' => 'Edit Project' ), 'menu-icon' => 'dashicons-media-document', 'public' => true, 'has_archive' => true, 'supports' => array( 'title', 'thumbnail', 'editor', 'excerpt', 'comments' // <- thumbnail not thumnail ) ) ); } add_action('init', 'gt_custom_post_type'); Also you’re lacking any internationalization in there...
stackexchange-wordpress
{ "answer_score": 0, "question_score": 1, "tags": "custom post types" }
How can I let the user choose size of a shoe in the store? I am making a shoe store in wordpress using Woocommerce. I just want to know if there is a way to let the user choose a shoe with a specific size. For example I want something like this: Screenshot Is this possible ? Thanks.
You can setup a Variable Product type and set a "size" product attribute. This will then let your users choose from a list of options. You will probably need to add some code to change the select dropdown into buttons to match your screenshot.
stackexchange-wordpress
{ "answer_score": 0, "question_score": -1, "tags": "woocommerce offtopic" }
Detect the activated theme from plugin code I would like to have my plugin detect the current "activated" theme. If my starter theme or the correct child theme is not loaded, then alert the administrator from wp-admin with an alert notification. I can figure out the latter, but it's the former I have a question about...are their hooks or conditional tags already built into WordPress that allows me to do this easily, or do most professional wp coders have their own custom logic of doing this? I'm ultimately building a plugin to assist & extend a specific starter theme. I want the plugin to detect this for the existing theme, and if a theme in the future is activated. Many thanks for the education!
You can use `wp_get_theme` to get current theme object. $current_theme = wp_get_theme(); And it will return WP_Theme object.
stackexchange-wordpress
{ "answer_score": 3, "question_score": 1, "tags": "plugins" }
After WP installation no GD lib recognition despite module is installed Centos 6 sys with php5.3.3, php5.6 and php7.0. Virtual Host set with php5.3.3 Just installed WP. Adding a plugin I get: > Adaptive Images Error — PHP GD image library missing > The PHP GD image library is not detected in your server. ... php -m | grep -i gd > gd rpm -qa | grep php > rh-php70-php-gd-7.0.27-1.el6.x86_64 > php-gd-5.3.3-49.el6.x86_64 I could successfully installed the same plugin in another WP installation (different virtual host, same server and php version) I have long time ago. I don't realize what's going on. I created the virtual host using Virtualmin. Also switched from 5.3.3 to 7.0 php version but GD wasn't found too
It was a Virtualmin control panel issue. It displayed a wrong php version used by this Virtual Host. Virtual hosts template is set to use 5.3.3 by default (user can change it later) and it is as it was displayed but phpinfo() displayed 5.6 w/o GD module. As stated in the question, only 5.3.3 and 7.0 were installed with DG from Virtualmin repositories. So I solved that installing GD for php5.6 from Centos repositories. I also have to point out that from Virtualmin CP I "changed" php version to php7.0 but it seems that was not successful because WP still complained about lacking GD.
stackexchange-wordpress
{ "answer_score": 0, "question_score": 0, "tags": "plugins" }
syntax error, unexpected '$id' (T_VARIABLE) - where is the issue though? This function below throws the following error: "syntax error, unexpected '$id' (T_VARIABLE)" This function and question is related to this post. function so328323_prefix_title( $title, $id = null ) { if ( get_post_type $id ) == 'tools-in-2019' { $title = "123 " . $title; } return $title; } add_filter( 'the_title', 'so328323_prefix_title', 10, 2 );
Here it is: if ( get_post_type $id ) == 'tools-in-2019' { Basically what your doing in this line makes no sense at all - you try to compare if conditions with some string... And you try to call a function, but you’re ignoring all PHP syntax. It should be like this: if ( get_post_type( $id ) == 'tools-in-2019' ) {
stackexchange-wordpress
{ "answer_score": 0, "question_score": -1, "tags": "functions" }
is_page_template not working Hi trying this code below to get working, but no look so far. Idea is simple if page template is **page-47.php** display `<h1>Something</h1>` else `<h1>This will show on any other page</h1>` . <?php if ( is_page_template( 'page-47.php' ) ): ?> <h1>Something</h1> <?php else: ?> <h1>This will show on any other page</h1> <?php endif ?> Thank You
`is_page_template()` will only tell you if the page is using a _custom_ page template. Meaning a template that was created by adding the `Template Name:` comment to the file and selecting it from the Template dropdown, as described here. The function works by checking the post meta for which template was selected. If you have created a page template using the slug or ID using the method described here, which you appear to have, then the template being used is not stored in meta, so won't be picked up by the `is_page_template()` function. If you want to know the filename of the current template being used, regardless of whether it's a custom template or not, you can use the global `$template` variable: global $template; if ( basename( $template ) === 'page-47.php' ) { }
stackexchange-wordpress
{ "answer_score": 16, "question_score": 7, "tags": "page template" }
Auth cookie value security risk? A short question this time: How much of a security risk is it when an third party gets access to WordPress auth cookie? Can they for example simply copy the cookie and "be" logged in as the user who was the original cookie owner? I ask this because i'm planning on passing the auth cookie value between different servers.
> Can they for example simply copy the cookie and "be" logged in as the user who was the original cookie owner? **Yes!** with the cookie they basically have your login session. You do not want 3rd parties to get the cookie. Keep in mind there is more than 1 cookie, for frontend and for backend. > I ask this because i'm planning on passing the auth cookie value between different servers. I would advise against sending the actual cookie across servers. This sounds like an XY problem question, where instead of asking how to solve problem `X`, you asked how to implement or fix solution `Y`. There are better ways to handle users across multiple servers ( some of which are a part of how cookies work ), but it would depend on what you're doing that necessitates this, you'd need to ask a new question ( possibly on another stack )
stackexchange-wordpress
{ "answer_score": 2, "question_score": 1, "tags": "security, cookies, authentication" }
Add item to admin panel - w/o plugin & theme I'd like to create a new page in the wp-admin panel. I know I should use the `add_menu_page()` function for that and I understand how it works. I'm new to WP development, and would just like to know in which file I should put this function. The doc does not answer to my question, or I don't understand it. I don't know if it's possible but I'd like this page to be part of neither the plugins nor the themes. Thanks for your help
As long as it gets registered before the `admin_menu` hook happens, it doesn't matter what file you put it in. The important part is what hook you call your function on. For simplicity sake you could put it in a themes `functions.php`. If you want things to look a bit cleaner then put it in a php file named `admin-menu.php` (or whatever explanatory name you want) and `require_once` that file from `functions.php` add_action('admin_menu', 'your_function_name'); function your_function_name() { add_menu_page(...)// add your menu page here }
stackexchange-wordpress
{ "answer_score": 0, "question_score": 0, "tags": "wp admin, add menu page" }
Custom CSS for viewing a draft page on the frontend? When viewing a draft page on the frontend, I'd like to see that status right away on the page itself. Currently, there is zero indication. Is there any way to have draft-specific CSS (or even just a header message?)
There is probably a better way but you could add the following CSS to your stylesheet, which will add a little banner when viewing a page that has a status of draft. .status-draft.hentry:before { content: "Previewing a Draft"; background: #87C5D6 !important; display: block; text-align: center; } You could also use these classes for the different statuses. `.status-pending` `.status-publish` `.status-future` `.status-private` Works for me. ![enter image description here](
stackexchange-wordpress
{ "answer_score": 5, "question_score": 3, "tags": "draft" }
RSS feed with specific keyword I am able to get articles as RSS feed from below url I am also able to get articles from BlogSpot with specific keywords as below I have tried to get articles from filtering with specific KEYWORD in wordpress blog but I am not able to get. What can be the URL. I am very much newbie to wordpress.
You can modify the list of posts displayed in feed using `pre_get_posts` action. And to target only feeds, you can use `is_feed` conditional tag. So such code can look like this: add_action( 'pre_get_posts', function ( $query ) { if ( ! is_admin() && is_feed() && $query->is_main_query() ) { if ( isset($_GET['q']) && trim($_GET['q']) ) { $query->set( 's', trim($_GET['q']) ); } } } ); This way you can go to `example.com/feed/?q=KEYWORD` and you'll get filtered feed (be careful - most browsers are caching feeds, so you'll have to force them to refresh it).
stackexchange-wordpress
{ "answer_score": 2, "question_score": 3, "tags": "wp query, actions, rss, pre get posts" }
change header height on 2017 theme for logged in users When a guest sees the homepage they see the (almost) full height picture which is quite nice I think. However, when a user logs in I'd like them to be redirected to the home page but with a much shorter picture (as the picture appears on the internal pages of the site). I know I could redirect logged in users to a faux front page, but is there a way of changing the height of the main header picture depending if the user is a guest or logged in?
WordPress will automatically add a body class to the body tag if a user is logged in. You could potentially use this to adjust the height. For example.. .logged-in #myElement { ...Your CSS } Something like this should work. .logged-in.twentyseventeen-front-page.has-header-image .custom-header-media { height: calc(70vh); } Note the calc 70vh is 70% of viewport height, so adjust to what you need.
stackexchange-wordpress
{ "answer_score": 0, "question_score": 0, "tags": "frontpage, theme twenty seventeen" }
Adding a widget under an 'Add to Cart' button through a PHP snippet Despite that my PHP knowledge is very scarce I've managed to add some elements under the add-to-cart button in my installation of Woocommerce with the function: add_action( 'woocommerce_after_add_to_cart_button', 'astra_add_woocommerce_payments', 97 ); function astra_add_woocommerce_payments() I'd like to also add a small currency converter calculator widget using the same function, if possible, but my Google-fu hasn't returned useful results. Do I need to access the source code of the plugin? is there an easy way to do it? where do I start? Hope to improve my programming skills bit by bit with your help guys. Thanks for your attention.
Your plugin for the converter supports shortcodes, so this is a good starting point. Everything should be as simple as using this code: add_action( 'woocommerce_after_add_to_cart_button', 'astra_add_woocommerce_payments', 97 ); function astra_add_woocommerce_payments(){ echo do_shortcode( '[currency_converter_calculator lg=”en” tz=”0″ fm=”EUR” to=”USD” st=”info” bg=”FFFFFF”][/currency_converter_calculator]' ); } You probably want to wrap the shortcode result inside a `div` or something to size it properly for your add to cart area. You can also take the "register sidebar" road and create a proper sidebar/widget area so you can control it from the backend, in that case take a look at this.
stackexchange-wordpress
{ "answer_score": 0, "question_score": 0, "tags": "php, woocommerce offtopic" }
Unable to declare AOS library in functions Greeting WP Devs, I am planning to transfer the script libraries in my function.php . In my function.php I registered AOS function mypage() { if ( is_page( 'mypage' ) ) { wp_register_script( 'aosjs', get_template_directory_uri() . 'js/aos.js', array( 'jquery' ), NULL, false ); wp_enqueue_script( 'aosjs' ); wp_enqueue_script( 'jquery.min' ); add_action( 'wp_enqueue_scripts', 'testingarea'); Page Name : **mypage** < \- My script has **cdn** with **AOS.init** <script src="js/aos.js"></script> <script> AOS.init({ easing: 'ease-in-out-sine' }); </script> **_First Test-_** AOS is registered in functions.php aand in mypage I removed the cdn in the mypage Page and aos init is still there but the result is ![enter image description here]( .. PLease kindly give me suggestions on how to declare this properly.
The function `get_template_directory_uri()` returns the path without trailing slash. So you need to write wp_register_script( 'aosjs', get_template_directory_uri() . '/js/aos.js',...) Note the slash before "js/aos.js". What good for is this line, the script file should already be loaded: <script src="js/aos.js"></script>
stackexchange-wordpress
{ "answer_score": 0, "question_score": 0, "tags": "functions, wp enqueue script, 404 error, library" }
Accidentally re-installed wordpress Big mistake. I accidentally installed wordpress over an existing install. I know that my data is probably still in the database. I'm hosted on bluehost. What can I do to recover my instance?
Thanks to @WebElaine, I checked with Bluehost and they had backed up my wordpress a couple of days ago. Whew! I had them restore it and heavyweightsoftware.com is back in business. Thanks, bluehost.com!
stackexchange-wordpress
{ "answer_score": 0, "question_score": 0, "tags": "installation, shared hosting" }
Checkout form looks terrible Im currently building my first ever wordpress theme however the checkout form just looks messy. I have tried changing some bits around with css but It all just looks our of line. ![screenshot]( I have tried changing the css styles for the form but it wont line up for my attempts by using margins and positions yet sadly no luck. Any help would be great :D
It sounds like there's a CSS conflict with your theme or another plugin. To troubleshoot the issue, deactivate each plugin, one at a time, to establish which one may be causing the problem. If that doesn't work, activate a different theme to see if that solves it. If it's your theme causing the issues, you'll need to use your browsers developer tools to identify which CSS is responsible. You can then override it via your own CSS. Alternatively, try and add this line to functions.php: add_filter( 'woocommerce_enqueue_styles', '__return_empty_array' ); This will strip all styles from WooCommerce so you can build your own. This is how I usually tackle WooCommerce styling as it allows me to have full control of the design. It's time consuming, but you can re-use your styles for future builds.
stackexchange-wordpress
{ "answer_score": 0, "question_score": 1, "tags": "woocommerce offtopic, css" }
PHP question: how to combine syntax? could someone please tell me where the mistake is in my PHP code? My PHP knowledge is extremely rudimentary although I have tried it with < :-D "translated" it should mean something like: * Single Post -> Show reading time: yes * Custom Post Type "wpdmpro" -> Show reading time: no The function for the reading time works per se, but not in the way I put it together concerning the combination with the CPT. With my code the reading time is not shown - neither in the CPT nor in the normal single post: // Reading Time if (function_exists('readingtime') ) if ( is_single() && ! 'wpdmpro' == get_post_type() ) { echo '<span class="text-sep text-sep-cat">/</span>'; echo readingtime(); } Thanks for your help.
This part is incorrect: if ( is_single() && ! 'wpdmpro' == get_post_type() ) That essentially means: if ( is_single() && false == get_post_type() ) { Which will never be true. To check if a value does not equal another value, use `!==`: if ( is_single() && 'wpdmpro' !== get_post_type() ) Also, the way you've combined the two `if` statements is hard to read and prone to errors. Instead, just add the first statement as a condition to the one statement: if ( function_exists('readingtime') && is_single() && 'wpdmpro' !== get_post_type() ) { echo '<span class="text-sep text-sep-cat">/</span>'; echo readingtime(); }
stackexchange-wordpress
{ "answer_score": 2, "question_score": 0, "tags": "custom post types, php, functions, comparison" }
Can't display product categories on woocommerce getting Invalid taxonomy? I am tried to display all product category with bellow function .. getting a error Invalid taxonomy .. it's was working fine last 2 installation.. function be_woocommerce_category_id(){ $categories_array = array(); $categories_array[0] = esc_html__('Choose a Category', 'shopstore'); $args = array( 'orderby' => 'title', 'order' => 'ASC', ); $categories = get_terms( 'product_cat', $args ); if( count($categories) > 0 ){ foreach( $categories as $category ){ $categories_array[$category->term_id] = $category->name; } } return $categories_array; }
> it's was working fine last 2 installation Those two installation _might_ still be on WordPress prior to version 4.5.0, and according to the reference: > Since 4.5.0, taxonomies should be passed via the ‘taxonomy’ argument in the `$args` array So: $args = array( 'orderby' => 'title', 'order' => 'ASC', 'taxonomy' => 'product_cat', ); $categories = get_terms( $args ); If that doesn't work, then maybe on the new installation, your code is executed before the `product_cat` taxonomy is registered.
stackexchange-wordpress
{ "answer_score": 1, "question_score": -1, "tags": "woocommerce offtopic" }
WooCommerce - Inconsistent Indexing of Orders Problem: The sequence of indexation of orders goes down like this: orders are from 1-20 in order, then jumps to 40 and further in order for some time. And periodically this happens. Tell me, if someone came across a similar or knows the principle on which this index is affixed. ![WooCommerce - Inconsistent Indexing](
That's right, it should be. The order number is the record ID in the database. ID is an auto-increment surrogate key. "Missed" IDs can belong to revisions, drafts, media files, etc.
stackexchange-wordpress
{ "answer_score": 1, "question_score": -1, "tags": "woocommerce offtopic" }
Return to the beginning of the results of a for loop I am currently doing a little script (and I am rather beginner), I would like to know how to return to the result number one of a for loop after the table containing the results have been traveled? here's the code: $currenttPostId = get_the_ID(); $theCategory = get_the_terms(get_the_ID(),'category'); $prevNext = array(); if (!empty($search_args)) { $search_args['posts_per_page'] = -1; for ($i = 0; $i < count($search_results); $i++) { if ( $search_results[$i]->ID == $currenttPostId ) { $prevNext[] = $search_results[$i - 1]; $prevNext[] = $search_results[$i + 1]; } } }
You can instantly access any position in an array by specifying the index. i.e. to get the first element of the $search_results array: $first_result = $search_results[0]; _Note if you're not used to working with arrays, they are "0" indexed in most languages, which means the first element's index is 0, the second is 1, etc._ This is what your loop is basically doing as well. Each time it accesses a different number directly, $search_results[$i] is just putting the value of $i in the same spot as I had the 0 above. You can **also** change the value of $i in your loop if you want to start the loop over, for instance. Adding the line: $i = 0; ...would send you back to the beginning. However I would not recommend you work with the index of a loop until you are quite comfortable with them.
stackexchange-wordpress
{ "answer_score": 0, "question_score": 0, "tags": "php, categories, loop" }
How do I make WordPress send an email to the user when his account gets approved (manual by me) I was wondering if I could make it so that if I approve a user account via "Users" UI that an automatic email is sent to the user saying something like "Hey, your account on www.website.com has been approved, thanks for your patience!" Is this possible in WordPress core, or is this something that has to be added manually? Thanks in advance.
What you are trying to do - approve a user in the admin and send an email - must be done using action and filter hooks, either by a plugin you're using or your own code in your child theme or a plugin. To approve a user, take a look at the `user_register`, `edit_user_profile`, `edit_user_profile_update` and `load-user-edit.php` hooks to get started. In your own approval code, you would then structure your email and send it with the `wp_mail()` function. Try searching the net for detailed solutions, you should be able to find blog posts with ready code.
stackexchange-wordpress
{ "answer_score": 0, "question_score": 1, "tags": "email, user registration" }
Component toggle not toggling I'm trying to create a checkbox in inspector controls that will change font size, but it doesn't get checked when clicked var CheckboxControl = wp.components.CheckboxControl el(FormToggle,{ help: 'If checked the text will show with large font', checked: false, label: 'Show large font', onChange: function(state){ props.setAttributes({ textSize: state }) } }) On the wordpress documentation the code seems different than mine and it can't apply to what I have. I see that there it's a piece of code that change it's state but I can't integrate it in my code: onChange={ ( isChecked ) => { setState( { isChecked } ) } }
I used this toggler to add a class to an element if checked. Maybe your goal is the same with a class for a larger font. I used it like this: checked: !!textSize, onChange: function(){ textSize ? props.setAttributes({ textSize: '' }) : props.setAttributes({ textSize: ' big' }) } So textSize controls the checked status and holds the classname, if checked. You can use the textSize string in other elements className: attributes.
stackexchange-wordpress
{ "answer_score": 0, "question_score": 0, "tags": "block editor" }
Debugging wp_query orderby for taxonomy I cannot seem to find where WP_Query adds the orderby clause to a SQL query. I am using this code: function wpd_team_taxonomy_queries( $query ) { if ( !is_admin() && $query->is_tax( 'team' ) && $query->is_main_query() ) { $query->set( 'orderby', " SUBSTRING_INDEX( t.name, ' ', -1 ) "); $query->set( 'order', 'ASC' ); } }add_action( 'pre_get_posts', 'wpd_team_taxonomy_queries' ); This works well apart from one particular taxonomy type, which I am debugging. I can see that WP_Query orderby parameter is set as above, but I cannot see in any of the queries from the DEBUG plugin or the Query Monitor plugin where the `SUBSTRING_INDEX( t.name, ' ', -1 )` code is added to a SQL query. Neither for the correctly ordering results nor the one that is not ordered. How would I find where this particular SQL query is built for orderby to debug this ?
You can't pass SQL directly as query parameters. The only valid values for `orderby` are covered in the docs for `WP_Query`. If you want to directly modify the SQL, you need to use the `posts_*` filters, in this case `posts_orderby`.
stackexchange-wordpress
{ "answer_score": 2, "question_score": 0, "tags": "wp query, order, sql, debug" }
SQL query to change the value of a Custom Field I am looking for a SQL query to change the value of a custom field, but not on all posts. Some posts have in the "post_template" custom field a "temp1" value, and I want to change this value to "temp4". Other values of this custom field must remain. I searched for the perfect query but nothing I found is working. Thanks.
If you're looking for raw SQL query, then this should help: UPDATE <PREFIX>postmeta SET meta_value = 'temp4' WHERE meta_value = 'temp1' AND meta_key = 'post_template' If you want to run this query from WP, then you can use this: global $wpdb; $wpdb->update( "{$wpdb->prefix}postmeta", array( 'meta_value' => 'temp4' ), array( 'meta_key' => 'post_template', 'meta_value' => 'temp1' ) );
stackexchange-wordpress
{ "answer_score": 0, "question_score": 0, "tags": "custom field, post meta, sql" }
How to align a text left side while keeping vertically centered? If you see this page, text are aligned left side but I also want them to align centered vertically. Similar to **Middle Align + Left Align** in excel. You can see this image to see what I am looking for ![enter image description here](
With flex: .question-content-text { display: flex; align-items: center; } Without flex: .question-content-text { position: relative; } .content-text { position: absolute; top: 50%; transform: translateY(-50%); }
stackexchange-wordpress
{ "answer_score": 0, "question_score": 0, "tags": "plugins" }
How to take shortcode and content separately from a page? I have a page with content and shortcode for the contact form. I want to display the content of the page in one div and the shortcode in another div(that means the form should render in another div). How to implement this? I tried `<?php remove_filter( 'the_content', 'do_shortcode', 11 ); the_content(); add_filter( 'the_content', 'do_shortcode', 11 );*/ ?>` for filtering the content only...but it displays the shortcode as it is.([contact-form-7 id="72" title="Contact form 1" html_class="col-lg-8 col-md-8 col-sm-12 col-12 dose-contact-form row"]).How to ffx this?
I found the solution. I used the following codes and it worked for me . To remove the shortcode from the content, I Used this `<?php $content = get_the_content(); $content = preg_replace("/\[.*]/m", " ", $content); $content = apply_filters('the_content', $content); $content = str_replace(']]>', ']]>', $content); echo $content; ?>` and the following code to get the shortcode only from post content ` <?php $pattern = get_shortcode_regex(); $matches = array(); preg_match_all("/$pattern/s", get_the_content(), $matches); echo preg_replace_callback( "/$pattern/s", 'do_shortcode_tag', $matches[0][0] ); ?>`
stackexchange-wordpress
{ "answer_score": 0, "question_score": 0, "tags": "filters, shortcode" }
Navigation menu disappears when I hover the mouse When I hover the mouse on submenu of our products section it automatically disappears, so I cannot click on the sub products. can you please help us out? website
> See in this screenshot < "li tag" is padding with red border so it is max height to consider li tag to hover sub menu if mouse cursor is go to below the red border then sub-menu is automatically disappears. so you can either reduce the font size of menu with padding or remove 2 items in menu then after it's working fine. Hope you got proper solutions.
stackexchange-wordpress
{ "answer_score": 0, "question_score": 0, "tags": "css, html" }
Print last modified date only on posts I'm printing the last modified date via functions.php with the following code function wpb_last_updated_date( $content ) { $u_time = get_the_time('U'); $u_modified_time = get_the_modified_time('U'); if ($u_modified_time >= $u_time + 86400) { $updated_date = get_the_modified_time('F jS, Y'); $updated_time = get_the_modified_time('h:i a'); $custom_content .= '<p class="last-updated">Last updated on '. $updated_date . ' at '. $updated_time .'</p>'; } $custom_content .= $content; return $custom_content; } add_filter( 'the_content', 'wpb_last_updated_date' ); The problem is that it appears on pages too, but I need to appear only on posts. Is there an `if` command to choose only blog posts? Thanks
You can check the post type with `get_post_type()`. You only want to display the content if the value is `post`: function wpb_last_updated_date( $content ) { $u_time = get_the_time( 'U' ); $u_modified_time = get_the_modified_time( 'U' ); if ( get_post_type() === 'post' ) { if ( $u_modified_time >= $u_time + 86400) { $updated_date = get_the_modified_time( 'F jS, Y' ); $updated_time = get_the_modified_time( 'h:i a' ); $custom_content = '<p class="last-updated">Last updated on '. $updated_date . ' at '. $updated_time .'</p>'; } } $custom_content .= $content; return $custom_content; } add_filter( 'the_content', 'wpb_last_updated_date' );
stackexchange-wordpress
{ "answer_score": 0, "question_score": 1, "tags": "php, functions, filters, date, date time" }
How to always display a specific post from the search result first I created a search filter that displays posts randomly, and I wonder how can I always display a specific post item in the first position of the search results and display the rest of the items normally. $taxonomies = array('recipe_type', 'product_category', 'recipe_category', 'recipe_event', 'recipe_diet'); foreach ($taxonomies as $taxonomy) { $taxonomies_taxonomy[$taxonomy] = get_taxonomy($taxonomy); $taxonomies_terms[$taxonomy] = get_terms( array( 'taxonomy' => $taxonomy, 'hide_empty' => false, 'meta_key' => 'filter_order', 'orderby' => 'meta_value_num', 'order' => 'ASC' ) ); $taxonomies_selected[$taxonomy] = (get_query_var($taxonomy)) ? get_query_var($taxonomy) : ''; }
One way to show a specific post always first is to add a sorting loop between your post query and rendering loop. For example, $my_posts = array(); // do your query first to get the posts $sorted_posts = array(); // helper var to store sorted posts // The sorting loop foreach ( $my_posts as $post ) { if ( "some logic here" ) { array_unshift($sorted_posts, $post); // use php function to prepend the post to the sorted array } else { $sorted_posts[] = $post; // just push the posts to the end of the sorted array } } // use $sorted_posts array in your rendering (foreach/while/for) loop
stackexchange-wordpress
{ "answer_score": 0, "question_score": 0, "tags": "filters, taxonomy, order" }
Facebook video on a post appears in a strange language I don't know why it happens but, when I copy and paste a Facebook video URL inside my blog post, the language switch into Hindi or Indonesian (I don't really know) < < Someone knows why?
It's a localization problem, Facebook is loading a who-know-where javascript sdk to embed the video. Switch to code view inside your wordpress editor and search for the js include url, similar to ` this, and change whatever string appears instead of `en_US` with `en_US`. Where the string is located depends on how you are doing the embedding.
stackexchange-wordpress
{ "answer_score": 0, "question_score": 0, "tags": "facebook, embed, videos, language" }
Display category names on edit user profile using $wpdb On the 'Edit Profile' page I'm trying to loop through all the category names using $wpdb. Here is my code <?php function custom_user_profile_fields($profileuser) { ?> <h1>Select a Category</h1> <select name="category"> <?php global $wpdb; $terms = $wpdb->query( "SELECT name FROM wp_terms" ); foreach ( $terms as $term ) { ?> <option value=""><?php echo $term; ?></option> <?php } ?> </select> <?php } add_action('show_user_profile', 'custom_user_profile_fields'); add_action('edit_user_profile', 'custom_user_profile_fields'); But I'm getting empty option filed.
The `$wpdb->query()` method doesn't return query results but a count on how many rows were affected by the query. To get the results you have to user the `$wpdb->get_results($sqlString)` method and then iterate over it. <?php function custom_user_profile_fields($profileuser) { ?> <h1>Select a Category</h1> <select name="category"> <?php global $wpdb; $terms = $wpdb->get_results( "SELECT name FROM wp_terms" ); foreach ( $terms as $term ) { ?> <option value=""><?php echo $term->name; ?></option> <?php } ?> </select> <?php } add_action('show_user_profile', 'custom_user_profile_fields'); add_action('edit_user_profile', 'custom_user_profile_fields');
stackexchange-wordpress
{ "answer_score": 1, "question_score": 0, "tags": "wpdb" }
Gutenberg Block checkbox check-unckeck does not work I have added the custom Gutenberg block for my shortcode, but in checkbox control check uncheck does not work, please check code done as below: el( components.CheckboxControl, { label: i18n.__( 'Display it?', 'txt-domain' ), checked: props.attributes.myAttr, onChange: function( val ) { if( val ) { props.setAttributes({ myAttr: '1' }) } else { props.setAttributes({ myAttr: '0' }) } } } ), if I remove the `checked: props.attributes.myAttr,` then it works fine but here, checkbox does not stay checked or uncheck. by the way it saves the value.
The property checked expects boolean value. (CheckboxControl) How did you define myAttr in attributes? If you set myAttr to '1' or '0' it is both true. Try empty instead of '0' `props.setAttributes({ myAttr: '' })` or false.
stackexchange-wordpress
{ "answer_score": 1, "question_score": 0, "tags": "block editor" }
TTFB is too slow in back-end the following picture is my TTFB screenshot. it`s very slow, so my website back-end is very slow !! < < How can I do to improve it ??
A simple solution (although not followed by good practices) would be to use a CACHE plugin. This will use an image of your HTML and you will not have to execute your process every time. If you want to improve the performance of the PHP file, you should find the root of the problem, that is normally queries to the database or some curl request within a loop, carried out inefficiently.
stackexchange-wordpress
{ "answer_score": 0, "question_score": 0, "tags": "performance" }
Migration / convert an existing site to WordPress I have an advertisement site that I create with PHP and MySQL. The structure of the database is very simple: * Tables: ads, type of ads, user, and images. * Each ad has an ad type (offer or request) * An ad has one or more associated images. * A user can post multiple ads. The site contains more than 10 thousand registered ads. How do I export data to a WordPress database?
Since it is a custom site and database structure, there is no easy way to import your data into WordPress. I would suggest you instead focus on how you would accomplish the same thing within WordPress. In other words, start by pretending you don't have those 1,000's of ads, and build out your way of tracking ads in WordPress. Then, when that works, you can think through if there's any way to move some of the data. If not, it would probably be easier to leave the old ads as-is and have the front-end run both implementations (pull from both data sources). You _could_ build a custom plugin that allowed you to continue using the custom database structure you already have, yet give you an editing capability through WordPress. After all, WordPress is quite comfortable with mySQL. So consider what you are hoping to gain by integrating the site with WordPress, how you would integrate it with WordPress in the first place, and then whether or not its worth bringing in your old data.
stackexchange-wordpress
{ "answer_score": 4, "question_score": 1, "tags": "migration" }
Generate dynamic ID's for each accordion button Hello my awesome WP peeps. I have a situation where I have an accordion and I want to add a show/hide all button for each new accordion I add. So I'm able to generate the post ID in the admin for each new button like: <button id='wp_1'></button> Im also able to add the jQuery code for an onclick event that will open the accordion like: $('#wp_1').on('click', function () { $('.panel-collapse').collapse('toggle'); }); The problem is, Im not sure how to generate multiple dynamic ID's so that each button only opens up the accordion below it. So in the screenshot below, how do I get WP to also generate an onlclick for #wp_31? Appreciate the help. ![screenshot of html](
I was able to solve this problem with using the jQuery closest method.I had to nest the button inside the container so the function would be able to return the first ancestor of that particular button element that is clicked. $(".toggle-button").on("click", function() { $(this).closest('.collapse-group').find('.wpsm_panel-collapse').collapse('toggle'); });
stackexchange-wordpress
{ "answer_score": 0, "question_score": 0, "tags": "jquery" }
How to call plugin function per site in a multisite? **My goal is to be able to call a plugin function per site and of course it has different result based on the site data.** e.g. I have a plugin called: **sample-plugin.php** Inside it has a function called: function sp_echo_site() { echo get_site_url(); } I have a multisite inside has 3 sites: e.g. animals.com, fruits.com and people.com And in a network level, I wanted to call the `sp_echo_site()` function. I wanted to do the following loop, however of course it doesn't work, How can I make this work? foreach (get_sites() as $site) { $site->sp_echo_site(); } How can i achieve the following result?: animals.com fruits.com people.com Is this possible? Or do I have to go to database? Or any other alternative methods?
You're almost there... If you have this in your plugin: function sp_echo_site() { echo get_site_url(); } Then you call this function as this: sp_echo_site(); And this line will run this function in the context of current site. So you'll have to do something like this: if ( function_exists( 'get_sites' ) ) { foreach ( get_sites() as $site ) { switch_to_blog( $site->blog_id ); sp_echo_site(); restore_current_blog(); } }
stackexchange-wordpress
{ "answer_score": 1, "question_score": 1, "tags": "php, plugin development, functions, multisite" }
How to get the custom post list to admin user edit page? I want to list out some post types in the admin panel admin user section to allow the users to access from the front end. How can i get the post list in admin user edit profile section? ![enter image description here](
Here are some steps that may help you: 1. Use show_user_profile action to insert a form in User edit page: 2. Use get_post_types function to get a list of registered posts in above form. 3. Finally use edit_user_profile_update action to save your data. Here is an example which shows how to add custom fields to user edit page.
stackexchange-wordpress
{ "answer_score": 1, "question_score": 0, "tags": "custom post types, wp admin" }
How to elect position of new item output in a dropdown when using add_filter Hello I am using the suggested snippet here to add a new term to a dropdown menu: < which is: add_filter( 'job_application_statuses', 'add_new_job_application_status' ); function add_new_job_application_status( $statuses ) { $statuses['example'] = _x( 'Example', 'job_application', 'wp-job-manager- applications' ); return $statuses; } That works fine but my new single entry 'example' is output at the bottom of the dropdown list, I'd really like it to be in 2nd place. Is there a simple way to do this? Thank you.
You can achieve this by using the array_splice() function in conjunction with array_merge(). Here is an example: function add_new_job_application_status( $statuses ) { return array_merge( array_splice( $statuses, 0, 1 ), array( 'example' => _x( 'Example', 'job_application', 'wp-job-manager- applications' ) ), array_splice( $statuses, 1, -1 ) ); } add_filter( 'job_application_statuses', 'add_new_job_application_status' ); This function takes the first item in the `$statuses` array, your custom example field, the rest of the items in the array and merges it together. You need to do it this way as splice doesn't support inserting a multi-dimensional array at a specific point in an array. Hope that helps.
stackexchange-wordpress
{ "answer_score": 0, "question_score": 0, "tags": "filters, hooks, dropdown" }
Loading page template into shortcode I am attempting to load a page template into a shortcode so I can easily load the content wherever I want. I have done some research and many people have said this code has worked for them but for some reason this does not seem to load my template right as I just get a blank page. I know the shortcode is executing as it does not show as plain text so I'm guessing there is a problem with the way I am loading the template. Any help is much appreciated . public function register(){ add_shortcode( 'sponsor_main_page', array($this,'my_form_shortcode') ); $RegistrationFormId = esc_attr( get_option( 'ik_form_id' ) ); } function my_form_shortcode() { ob_start(); get_template_part( 'template-sponsors.php' ); return ob_get_clean(); }
`get_template_part` takes slug as first parameter and not filename. So it should be: get_template_part( 'template-sponsors' ); And with more details... This function takes two parameters: get_template_part( string $slug, string $name = null ) And inside of it, the name of a file is built like this: if ( '' !== $name ) $templates[] = "{$slug}-{$name}.php"; $templates[] = "{$slug}.php"; So, as you can see, the `.php` part is added automatically. So your code will try to load file called `template-sponsors.php.php` and there is no such file, I guess.
stackexchange-wordpress
{ "answer_score": 3, "question_score": 2, "tags": "php, plugin development, shortcode, page template" }
Title has word broken when viewed in mobile I am designing a website using the Renden Free theme, and my problem is that some long titles, when viewed in mobile, have words broken in half. For example: ![Screenshot]( As you can see, the word "Corporal" gets broken and split in two lines. Why is this? Is there any way to control where does Wordpress split the title?
It's possible that a word-break CSS rule could fix the problem. You could apply it globally with this body {word-break:normal !important; } Or maybe this: body {overflow-wrap: normal;} But it might be better to apply that to the specific class/id used by the title. And ever further tweak it to only apply that rule to smaller screens via the media query. But you could add the above to 'additional CSS' in your theme customization to see if that will help. Asking the theme developer support area is the best place for this question, though.
stackexchange-wordpress
{ "answer_score": 2, "question_score": 0, "tags": "css, html, responsive, screen layout" }
Multiple pagename WP Query I wonder if I can use `WP_Query()` with multiple slug like `p => array(1,2,3)` I have tried using `pagename => array('accommodation','activities','restaurant')` but pagename expects a string and doesn't accept arrays. * * * How do I Query multiple page using the page slug?
For multiple _slugs_ , you can use `post_name__in`: new WP_Query( array( 'post_name__in' => array( 'accommodation','activities','restaurant' ), ) ); For multiple _post IDs_ , you can use `post__in`: new WP_Query( array( 'post__in' => array( 1, 2, 3 ), ) ); You can check the Codex for more details.
stackexchange-wordpress
{ "answer_score": 1, "question_score": 0, "tags": "wp query" }
get parent and childs from hierarchcial taxonomy I have a hierarchical taxonomy and I want to show only children from 1 parent. For example, the taxonomy looks like this: - Events -- Location -- Date - Region -- State -- StateCode When I use my code, I get all child values... $terms = get_terms( array( 'taxonomy' => 'events_category', 'hide_empty' => false, ) ); foreach ($terms as $term) { if ($term->parent != 0) { // avoid parent categories $options[] = array('label' => $term->name, 'value' => $term->term_id, 'id' => $term->term_id); } } Is it possible, that I can modify this lines to get only the children from Events for example?
Yes, you can. `get_terms` function takes `$args` as first param. And you can use the same args as with `WP_Term_Query`. Two arguments that may interest you are: * `child_of` \- (int) Term ID to retrieve child terms of. If multiple taxonomies are passed, $child_of is ignored. Default 0. * `parent` \- (int|string) Parent term ID to retrieve direct-child terms of. So if you want to get only the terms that are children of Event term, then you can use this code: $terms = get_terms( array( 'taxonomy' => 'events_category', 'hide_empty' => false, 'child_of' => <EVENTS_TERM_ID>, // <-- you have to replace this with the term id of Events term. ) ); This way you don't need any `if`s in printing code any more.
stackexchange-wordpress
{ "answer_score": 0, "question_score": 0, "tags": "custom taxonomy, terms" }
Remove formatting in rich text with Gutenbergs Block editor In the classic editor, an option for removing all formatting in a selected text was possible in the visual tab. Is there such a function for Gutenberg? If not, is it planned at some point? What would be the easiest workflow for establishing a 'clear all tags and links' procedure in your opinion with Gutenberg without such an option?
I'm afraid there is no such function in there yet. You can find this bug: < and it's still open as enhancement. On the other hand, you can paste using Cmd+Shift+V (Ctrl+Shift+V on Win) and it should paste your text ignoring most of formatting, I guess.
stackexchange-wordpress
{ "answer_score": 1, "question_score": 0, "tags": "block editor, formatting, workflow" }
Updater user with multiple roles I have searched the net for explanations, but I only find my own question without any real answer. Like this one: Adding multiple user roles dynamically I need to dynamically assign more than one role to some users. However, it seems that WordPress core is built for only one role per user. I have used Members plugin to define more roles. And they seem to reside in wp_options, along with the 'native' ones. But it seems impossible to update the user->role with an array. Any suggestions?
Roles are assigned one per user. That's default for WordPress. Instead of using roles, I recommend using capabilities to keep track of different types of users. You can assign multiple capabilities per user and set some default capabilities for the role. See: `add_cap()` and `remove_cap()`
stackexchange-wordpress
{ "answer_score": 2, "question_score": 0, "tags": "user roles" }
Sub Menus will not work I am desperately needing help. I have done everything to my knowledge to try to get my sub menus back on my website. I installed a meta slider plugin to get a slider on my homepage. It worked well and then after that, my sub menus stopped working! I then deactivated the plugin, thinking that is what caused it, and the sub menus still did not show up on my website. Not sure if I am missing code or what, but I will appreciate any help I can get. I also have the hemmingway theme, not sure if that has anything to do with it.
The problem is your sub menus are hidden behind your header wrapper because the overflow is set to hidden. ![enter image description here]( So a quick fix would be to go to `Admin > Appearance > Customize > Additional CSS` and paste in the following CSS. This will allow the overflow content to be visible. .header-cover { overflow-y: visible; } Note: I have no idea what you changed to cause this or if this has any adverse effects to your site so be sure to test it out.
stackexchange-wordpress
{ "answer_score": 0, "question_score": 0, "tags": "menus" }
Override theme style rule in Gutenberg I have a theme that adds the following CSS rule inline through the Customizer to style the hover state of links in post content: .entry-content a:hover { color: <color selected in the Customizer>; } I'm adding support for Gutenberg in my theme and I'm having some issues with the link button block. The previous rule is overriding the following default core block style rule that applies the same link button color selected in Gutenberg for the button active, focus and hover states: .wp-block-button__link:active, .wp-block-button__link:focus, .wp-block-button__link:hover { color: inherit; } Checking the Inspector, I see that the last rule applied is the first one instead of the second one, which I thought it was more specific. That means that the link button color selected in Gutenberg is not honored. Any ideas on how to fix this? Thanks in advance
`.entry-content a:hover` is more specific than `.wp-block-button__link:hover`. According to the rules of specificity, the first selector contains 2 class selectors (`.entry-content` and `:hover`), and 1 type selector (`a`), for a specificity score of `0,0,2,1`. The second selector, on the other hand, contains 2 class selectors (`.wp-block-button__link` and `:hover`), and no type selectors, for a score of `0,0,2,0`. It wasn't clear to me from your question where exactly the second set of selectors was coming from, but assuming that you can't edit them, the solution would be to exclude Gutenberg buttons from your original selector. You can do this with the `:not` pseudo class: .entry-content a:not(.wp-block-button__link):hover { color: <color selected in the Customizer>; } Now your Customizer-selected colour will only apply to links that are not block editor/Gutenberg buttons.
stackexchange-wordpress
{ "answer_score": 1, "question_score": 0, "tags": "theme customizer, block editor, css" }
Set custom post type terms by id without knowing taxonomy For a custom post type with multiple taxonomies, is it possible to set the post terms without explicitly knowing which taxonomy the term falls under? I have an array of term ids which may contain a mix of terms from any one of three taxonomies. The only function I've found to add terms to a cpt is `wp_set_post_terms` which requires the taxonomy slug.
It's a bit confusing, the documentation for `wp_set_post_terms()` claims that the `$taxonomy` argument is "Optional", but in looking at the source it appears that all this means is that its default value is `post_tag` if you omit the argument. If you attempt to pass `null` or an empty string, it won't work. So I think the solution then would be to first get the taxonomies of the given IDs, and then set the terms for each taxonomy separately. $post_id = 123; // For example. $term_ids = [ 1, 2, 3 ]; // For example. $terms = []; foreach ( $term_ids as $term_id ) { $term = get_term( $term_id ); $terms[$term->taxonomy][] = $term_id; } foreach ( $terms as $taxonomy => $term_ids ) { wp_set_post_terms( $post_id, $term_ids, $taxonomy ); }
stackexchange-wordpress
{ "answer_score": 2, "question_score": 1, "tags": "custom taxonomy, terms" }
Posting or Updating Article Fails on WordPress I have a **Update failed** when I update an article. The article is well updated, or published, but I have this error in red. ![enter image description here](
Ok, it's Instant Articles plugin from Facebook with an invalid access token page...
stackexchange-wordpress
{ "answer_score": 0, "question_score": 0, "tags": "posts" }
HTTP ERROR 500 after installing child-theme [Wordpress] I just created and activated a child theme and now I'm getting the HTTP ERROR 500. I've deleted the child theme through FTP and still getting the error. Also tried changing `wp-content/themes` to `wp-content/themestemp` and that allows me to get back into the wp-admin panel but when I'm trying to install a new theme Wordpress can't create a new directory for the themes. Is there a way to recover the primary theme? Thanks in advance!
In general a `500 Server Error` can be solved (or at least be correctly identified) by looking at php logs. If you are on a shared hosting you should have something in your hosting's control panel to check the logs (look for `Error` messages), if you are self-hosting on your own vps you can usually find the logs in the `/var/log` directory. This said, the current theme in WP is stored as two entries in `wp_options`, which are `template` and `stylesheet`. Name back the theme directory like the original one, write down the directory name of the original theme, and put it as the field value for `wp_options.template` and `wp_options.stylesheet`. At this point Wordpress is, if you haven't touched anything, be in the same state as before you child-theme'd. Refer to the first paragraph of my answer and edit the answer with the php error so we can look at it.
stackexchange-wordpress
{ "answer_score": 1, "question_score": 0, "tags": "php, server, 500 internal error, internal server error" }
Rewrite rule not working, issue may be in URI request I'm trying to make a rewrite rule so that posts can be accessed both at the default < and at < The code below is what I have so far. It extracts the slug from the address, uses the slug to get the post ID, and puts the slug and ID into the final rule. function my_rewrite_rule() { $path = $_SERVER['REQUEST_URI']; $slug = basename($path); $url = ' . $slug; $post_id = url_to_postid($url); add_rewrite_rule('^prefix/section2/' . $slug, 'index.php?p=' . $post_id, 'top'); } add_action('init', 'my_rewrite_rule'); When I echo the variables, they are all correct, but when I run the rule, the second URL format gets a 404 error. The problem seems to be related to `$path = $_SERVER['REQUEST_URI']`. When I supply `$path` manually, the rule works.
I think you should do something like this: function my_rewrite_rule() { add_rewrite_rule('^prefix/section/([0-9]+)/([^/]*)?', 'index.php?section=$matches[1]&name=$matches[2]&post_type=post', 'top'); } add_action('init', 'my_rewrite_rule'); Add a query var for section: function my_query_vars( $vars ) { $vars[] = 'section'; return $vars; } add_action( 'query_vars', 'my_query_vars' ); I created the pattern for your section (which can be 1 or 2) and used $matches[2] to set the "name" parameter, which is your slug. Then I set the "post_type" to "post" to be sure WordPress is searching for a post. Because I added the query var you can then do: $section = get_query_var( 'section' ); To know which section is loaded.
stackexchange-wordpress
{ "answer_score": 0, "question_score": 0, "tags": "rewrite rules" }
Why do I have categories with duplicate slugs? I have inherited a WordPress site, where I'm trying to resolve a weird-looking issue related to post categories. In the `Edit Post` page, there is nothing showing up under `Categories` (Gutenberg editor). ![missing categories]( Thinking this is strange, I went to the `Categories` page. There, I saw many categories with the same slug. ![list of duplicate posts]( This is even more strange to me, since I thought categories couldn't have the same slug. I figure this is where the issue lies. So I'd like to start deleting these duplicate categories, but there is no `Delete` link – only `View`. ![view button visible, but not delete]( Can anyone shed some light on what might be happening here? Can I fix this directly in the database somehow?
I found a few rows in the `wp_terms` table with a `term_id` of `0`. There was also some entries in `wp_term_taxonomy` with `term_taxonomy_id` and `term_id` both set to `0`. After deleting all of those rows, behaviour returned to normal. Also, I had to fix some issues with the database structure. In the `wp_terms` table, I had to make sure that `AUTO_INCREMENT` was enabled for the primary key field.
stackexchange-wordpress
{ "answer_score": 0, "question_score": 0, "tags": "posts, categories, tags" }
Does WordPress still ask for FTP credentials for each file operation? There is a reply from 2014, that is a great answer to a question I have, but WordPress changes, and I'm wondering if this is still true, "WP Filesystem API will ask for FTP credentials, but it will do so for each operation. They aren't stored persistently." Where does wordpress store the FTP credentials? If this is still true, I'm guessing that the interaction between WordPress and the host would be that the host would send the default (main) FTP credentials unless a specific account were added to wp-config.
Not quite right. WordPress only requests FTP credentials if it cannot modify files. That's the important bit from Rarst's reply. This all comes down to who owns the files and does php (and WordPress) have access via either the group and/or user to modify these files? The default is to use php's filesystem extension which does not require FTP at all. In the case of using FTP, credentials would always need to be set either within the WordPress admin for each request or in wp-config.php. Here's a good overview of what's going on: What security concerns should I have when setting FS_METHOD to "direct" in wp-config? The codex for `FS_METHOD` lists the different options for WordPress interacting with the file system. To answer your question, nothing has changed with regards to the way WordPress interacts with the filesystem with regards to FTP. Hope that helps!
stackexchange-wordpress
{ "answer_score": 1, "question_score": 0, "tags": "ftp, filesystem api" }
Add a containing DIV to core Gutenberg blocks The design I am working with calls for each Gutenberg block to have a coloured background (white in this case) with `max-width: 1160px` and the content within to have `max-width: 800px` and centered. Similar to the image below: ![enter image description here]( Which would need a setup like this: <main class="site-background"> <div class="width-1160"> <p class="width-800">Some text content...</p> </div> </main> At this time we are only using core Gutenberg blocks but the markup it produces is similar to the below, without the containing `<div>`: <main class="site-background"> <p class="width-800">Some text content...</p> </main> Is there a way to add a containing `<div>` to all Gutenberg content blocks that will be safe when core updates?
I'm sure there are other ways e.g. with CSS only or Add custom class to core blocks in Gutenberg, but regarding: > Add a containing DIV to core Gutenberg blocks one way could be with the `render_block` filter: add_filter( 'render_block', function( $block_content, $block ) { // Target core/* and core-embed/* blocks. if ( preg_match( '~^core/|core-embed/~', $block['blockName'] ) ) { $block_content = sprintf( '<div class="some__class">%s</div>', $block_content ); } return $block_content; }, PHP_INT_MAX - 1, 2 ); to div-wrap the core blocks on the frontend. Changing the HTML layout might affect the current style of the site.
stackexchange-wordpress
{ "answer_score": 2, "question_score": 2, "tags": "customization, block editor" }
Custom taxonomies I have created a custom taxonomy 'regionen'. I have two levels inside the taxonomy Anden \- Peru \- Bolivian Conosur \- Chile \- Argentinien I'm calling the taxonomy on the home page like this ('see below') and it lists all the terms for each post. Example Anden, Peru. <?php the_terms( get_the_id(), 'regionen' ); ?> What I would like to do is just call the relevant top level term 'Anden or Conosur' for each post on my index page and the second level term only on my single post pages?? Hopefully that makes sense and someone help explain this to me. Thanks for taking the time to read my problem.
You can use `get_the_terms( int|WP_Post $post, string $taxonomy )` . See Codex detail here. $my_terms = get_the_terms( get_the_id(), 'regionen' ); if ( ! empty( $my_terms ) ) { if ( ! is_wp_error( $my_terms ) ) { echo '<ul>'; foreach( $my_terms as $term ) { if($term->parent == 0){ echo '<li><a href="' . get_term_link( $term->slug, 'regionen' ) . '">' . esc_html( $term->name ) . '</a></li>'; } } echo '</ul>'; } }
stackexchange-wordpress
{ "answer_score": 4, "question_score": 2, "tags": "custom taxonomy" }
How to pass parameters from jQuery ajax into PHP function? I have this: PHP: add_action('wp_ajax_count_messages', 'count_messages'); function count_messages($projectid) { //some code wp_send_json_success($projectid); } JS: var countData = { 'action': 'count_messages', 'projectid': '100' } var myRequest = $.ajax({ url: admin_ajax.ajax_url, type: 'post', data: countData }); myRequest.done(function(data){ console.log(data); }); When I check console, I get: {success: true, data: ""} I am not sure what is happening and why I get an empty string?
The data you send from jQuey to PHP is in the `$_POST` variable. So you can use `$_POST['projectid']` inside your PHP function to get the data.
stackexchange-wordpress
{ "answer_score": 0, "question_score": 0, "tags": "ajax, jquery" }
How to modify query so it grabs only 90 posts in total? I want to have 3 Pages with 30 posts each: **Total 90 posts.** **/page/4/ shouldn't exist**. Should either 404 or redirect to home. Only /, /page/2/ and /page/3/ should exist. With 30 posts each, like so: * / _posts -> 01-30_ * /page/2/ _posts -> 31-60_ * /page/3/ _posts -> 61-90_ I've tried numerous suggestions, none limit the query for me. Just the number of posts per page. This looked promising but has no effect (/page/999/ works) function wpcodex_filter_main_search_post_limits( $limit, $query ) { if ($query->is_front_page()) { //this: return '90'; //or even this: return 'LIMIT 90'; } return $limit; } add_filter( 'post_limits', 'wpcodex_filter_main_search_post_limits', 10, 2 ); Some people as a work around suggest counting with PHP and using an if to stop showing the posts. That's a work around i want to limit the SQL query.
Try using `paginate_links( $args )`. Here is code adopted from codex. $paged = ( get_query_var( 'paged' ) ) ? absint( get_query_var( 'paged' ) ) : 1; $args = array( 'posts_per_page' => 30, 'paged' => $paged, ); $the_query = new WP_Query( $args ); // the loop etc goes here.. $big = 999999999; echo paginate_links( array( 'base' => str_replace( $big, '%#%', esc_url( get_pagenum_link( $big ) ) ), 'format' => '?paged=%#%', 'current' => max( 1, get_query_var('paged') ), 'prev_next' => false, 'total' => 3 ) ); See detail here on codex.
stackexchange-wordpress
{ "answer_score": 1, "question_score": 0, "tags": "wp query" }
Show text only to the author of the article How can I be displayed in an article written by a writer in a text format only to the same author.
I came to a conclusion ! if ($current_user->ID == $post->post_author)
stackexchange-wordpress
{ "answer_score": 0, "question_score": 0, "tags": "author" }
How do I visualize the author's post from the front end? Currently posts are created automatically with an importer and I want the user to be able to see their own post. I already have the code to display the personalized post and the button to modify it. But how do I show it in a link in the menu or widget? Thanks!!
You can get a list of posts created by each user using /author/{username} Eg : <
stackexchange-wordpress
{ "answer_score": 0, "question_score": 0, "tags": "php, buddypress" }
Issue while installing wordpress in subdirectory due to SSL Here is the case, my oracle fusion website was initially installed without SSL, last year using plugin “Really Simple SSL” plugin and following this article I changed it to HTTPS. Now my hosting provider is providing free SSL, the problem is, if I install another wordpress in subdirectory < i cannot access wordpress backend. You can see it by navigating to < Note : I used Softaculous to install wordpress in subdirectory and selected https:// protocol. Thanks Avinash
This was resolved after enabling SSL level to FULL on cloudflare.
stackexchange-wordpress
{ "answer_score": 0, "question_score": 0, "tags": "subdomains, ssl" }
Config.php issue in WordPress have recently Encountered an issue on my website. Not sure when or how this happened. I am getting the following message displayed on-top of all my web-pages on this specific site. ” Notice: Constant FS_CHMOD_DIR already defined in /home/mc4ebqy52sd6/public_html/khwajagharibnawaz.org/wp-config.php on line 101 ” The website is khwajagharibnawaz.org I am a armature on WordPress however,I had a look at the config.php file and the l01 line is just a text line stating the following : 100* For information on other constants that can be used for debugging, 101* visit the Codex. 102* Any help to resolve this issue would be highly appreciative.
Look for `FS_CHMOD_DIR` in wp-config.php. You can only define constants once. If it's defined multiple times, you will get a PHP notice. Notices aren't often a cause for concern, but they can reveal places you may have issues across the site. You can disable these from displaying to your visitors by defining `WP_DEBUG` as false.
stackexchange-wordpress
{ "answer_score": 2, "question_score": 0, "tags": "wp query, errors" }
How to get "nexepagelink" and "previoiuspagelink" in wp_link_pages? I'm trying to get pagination in my pages, so I use this default option: <?php wp_link_pages( array( 'before' => '<div>', 'after' => '</div>', 'link_before' => '<span class="page-numbers">', 'link_after' => '</span>', 'next_or_number' => 'number', 'separator' => ' ', 'nextpagelink' => __( 'Next page', 'behold-universal-one'), 'previouspagelink' => __( 'Previous page', 'behold-universal-one' ), )); ?> works all except "nextpagelink" and "previouspagelink". No matter what I use, no text next or previus pages is visible. Ofcourse there is more than one page break. Wordpress 5.1 Any ideas why?
`wp_link_pages()` doesn't support numbers _and_ next/previous links. If you set `next_or_number` to `number`, the default, then the pages will be shown as number links. By default that looks like this: Pages: 1 2 3 If you set it to `next` then you'll get this output: Pages:Previous page Next page The `nextpagelink` and `previouspagelink` arguments are used to changed those labels, but they won't add next and previous links to the numbered pagination.
stackexchange-wordpress
{ "answer_score": 1, "question_score": 1, "tags": "pagination, navigation" }
How to get posts without author? I am looking for a way to get all posts without author. They were inserted with post_author = 0; But the following line returns all posts instead of the posts with no/null author get_posts( array('author' => 0 )); How to get posts without author?
That won't be as easy as you'd like to... `get_posts` uses `WP_Query` to get posts and if you take a look at `WP_Query` code, ten you'll see, that 0 is used as empty in there (< if ( ! empty( $q['author'] ) && $q['author'] != '0' ) { It means, that you can't pass `'author' => 0` and get posts that have 0 as author. And that's correct behavior, because 0 is not a valid value for `post_author` column - this column should contain ID of existing user. On the other hand, if you already have 0s in there, then you'll have to use custom SQL to get these posts. One way to do this will be with this code: global $wpdb; $ids = wp_list_pluck( $wpdb->get_results( "SELECT ID FROM {$wpdb->posts} WHERE post_type=post AND post_author=0" ), 'ID' ); $posts = get_posts( array( 'post__in' => $ids, 'posts_per_page' => -1 ) );
stackexchange-wordpress
{ "answer_score": 2, "question_score": 0, "tags": "author, get posts" }
Remove a shortcode from all Wordpress posts I changed a wordpress theme on an old site and removed all plugins which were unnecessary. All went well except for a shortcode that was used by the earlier author shows up on every post. For example, > Lorem ipsum dolor sit amet, consectetur adipiscing elit. Aenean eu faucibus ipsum, id sagittis diam. Nam cursus ipsum quis dictum iaculis. > > [spacer height=”10px”] > > Quisque pellentesque risus risus, convallis consectetur odio malesuada non. Vivamus quis consequat diam. Nullam ac molestie purus. Vivamus id diam molestie, pulvinar urna eu, luctus purus. Sed ut cursus diam, sit amet tincidunt arcu. Integer blandit aliquam porttitor. > > [spacer height=”5px”] > > In consectetur dolor nulla, quis efficitur lectus tristique eu. Is there a way I can remove this using the database on phpmyadmin. When I search the term it shows up in many places but I don't know more than this.
I love to use this tool, Search and Replace for WordPress Databases. It is basically a PHP script that is written for WordPress usage (but of course can be used with any database). When placed in the WordPress project, it automatically detects and loads the Database using data from `wp-config.php` file. It enables you to make database queries based on regex, with a 'dry runs' - you will see a preview of the data that will be changed, but no real changes would be made. Also, it is serialization aware, meaning, if the variable you are replacing is inside a serialized object, it will safely be replaced, without breaking the serialization. Setup is easy, just drop the folder in the WP root, and navigate the browser to the main PHP file. Remember to remove it afterwards. I think you will love it as well, but remember to backup and double check before any live runs.
stackexchange-wordpress
{ "answer_score": 1, "question_score": 0, "tags": "posts, database, mysql" }
How to call Primary Category for WordPress Woocommerce I have try for several hours to solve this but I am getting nowhere. In the class-wc-structured-data I would like to add a Markup for "brand" as on my website the brand = the parent category `$markup['brand'] = $term = get_term_by('name', $name, 'product_cat');` I would like to call the wooocommerce parent category. With the above code I am getting the name as "False" instead of the parent category. Can someone help me please ? Thanks FYI I know little coding.
As per **WordPress Codex** for the function get_term_by( $field, $value, $taxonomy, $output, $filter ); > If `$value` does not exist, the return value will be `false`. If `$taxonomy` exists and `$field` and `$value` combinations exist, the Term will be returned. So, you need to check the value of `$name` in your code $term = get_term_by('name', $name, 'product_cat'); $markup['brand'] = $term ;
stackexchange-wordpress
{ "answer_score": 0, "question_score": 0, "tags": "categories" }
Disable Mobile Menu, (always show desktop menu) I’m having trouble with something. I have a (almost) one page website with only my logo in the header/top-bar but no other menu items. But when i see my site on a mobile device it does switch to a mobile menu (hamburger menu) and i dont want that preferably. I always want to show my header/top-bar like it is on desktop version with only my logo in it. I have tried a lot but havent found how to do this. Any suggestions? Thank you for the effort! Bye. Theme: Gateway (<
In your browser, hit `F12` to inspect your mobile menu. If you resize your browser between 640px & 641px you can see the different styles being applied. You just need to override the styles for mobile. Here is what I came up with. Paste these styles in `Admin > Appearance > Customize > Additional CSS`. .top-bar .title-area { float: left !important; } section.top-bar-section { display: inline-block !important; } .top-bar-section li.active:not(.has-form) a:not(.button) { padding: 0 21.66667px !important; line-height: 65px !important; }
stackexchange-wordpress
{ "answer_score": 0, "question_score": 0, "tags": "menus" }
Why does a header location on admin_head remove the query var I'm setting in the location? I have the following code which I thought would load the location with a query var of saved=1. public function __construct() { add_action( 'admin_head', array( $this, 'test' ) ); } public function test() { if( $_GET['test'] == 1 ) { header( "Location: admin.php?page=my-page&saved=1" ); exit; } } I am expecting to go to: And the resulting page to be loaded as: But the query var gets removed? Why?
If you want to perform any redirects, you have to send your header before site sends any output. `admin_head` is an action that allows you to print your custom code inside `<head>` tag of admin sites. But if it's inside of `<head>`, then some output is already sent to the browser, so you can't perform any redirections any more. As you can see here Actions Run During an Admin Page Request, the `admin_head` is called after the scripts and styles are already printed. So you should run your code using some hook that is fired before any output is sent to the browser. You can use `wp` hook for example. PS. Another thing is that you shouldn't use `header( "Location: admin.php?page=my-page&saved=1" );`. Using `wp_redirect` would be much nicer way to do this.
stackexchange-wordpress
{ "answer_score": 0, "question_score": 0, "tags": "php, query, query variable" }
Ajax call works for logged in users and returns "Bad Request" for guests I have a WordPress site that uses ajax to submit a form on the Front-end. When the form is submitted by a logged-in user, all works fine. When the form is submitted by not-logged-in user, I get a "Bad Request" error. Here is my code: **JS:** $('form').on('submit', function (e) { e.preventDefault(); // Submit the POST request $.ajax({ url: jsobject.ajaxurl, method: 'POST', data: { action: 'fe_submit_form' } }); }); **PHP:** function fe_submit_form() { ... } add_action( 'wp_ajax_fe_submit_form', 'fe_submit_form' ); When the user is logged in, all works fine. When the user is not logged it, I never go inside of the "fe_submit_form" php function. Any ideas?
The action for non-logged in users is `wp_ajax_nopriv_{$action}`.
stackexchange-wordpress
{ "answer_score": 0, "question_score": 0, "tags": "ajax, actions, json" }
Specifying meta field's column type in Database using add_post_meta In my code, I enhance one of my content types by following code: `add_post_meta( $post->ID, 'favourite_fruit_code', $value )` All goes well, but I would like to have power over specifying what a column type I would like to create in DB. There are cases when we would need different DB column types would be appropriate - depending on data we are going to store. How can I specify this? (For example if I want my field to be stored in DB as `TinyIntegerField`, or `BigIntegerField`, etc.).
When you use `add_post_meta`, no column in database is created. All post meta data is stored in `wp_postmeta` table (< Here's the structure of that table: ![enter image description here]( * `post_id` is the ID of post that this meta data is assigned to * `meta_key` is the key of meta (in your case `favourite_fruit_code`) * `meta_value` is the value of that meta So you're not able to set the type of column, because there is no column, and you're not able to set the type of value, because all values are stored as LONGTEXT. On the other hand, there is no need for setting the type of this column. You should sanitize and validate the values before setting them, and you can use `meta_type` in your meta query, so the values are compared correctly.
stackexchange-wordpress
{ "answer_score": 2, "question_score": 0, "tags": "custom post types, custom field, database" }
404 page not found - Yet open admin page it works Having a weird problem on a new site we are putting together. Everything is working OK with one exception - one page always returns a 404 page not found. In the admin pages, if the page is veiwed or previewed it works fine - in fact, if I open the site in another browesr tab - the site works fine. As soon as I log out of close the admin page, the very same page when refreshed comes up as 404 page not found. I've tried the ususal disabling plug ins, even tried refreshing permalinks - which was a disaster as the category posts on the front page started showing all the text instead of just the featured image. Its back to "normal" now - but even creating a new post with the same name doesn't work I really don't understand whats going on here - seems to have a mind of its own! Any ideas would be greatly appreciated - although seemingly a simple problem is is proving to be a show stopper!
I would be interested in what the page slug is...perhaps some non-ASCII characters in there? And, what happens if you change the page slug? Maybe there is another component in the page request that is causing the 404. Look at all request for that page (via Developer Tools in your browser) to see which request is the 404.
stackexchange-wordpress
{ "answer_score": 0, "question_score": 0, "tags": "permalinks, wp admin, 404 error" }
Limit the total space in every user I use the buddypress + rtmedia plugins to create website. And I met a problem that how can I **limit the total space** in every user ? **for example** every user has 10MB to upload the video,photo,music in their profile. or every user can upload 10 photos in their profile. can that do it via theme`s functions.php ?
It's a task that can be easily tackled using `wp_handle_upload` and `wp_handle_upload_prefilter` (e.g.: Give users a maximum upload capacity; limit the number of files a user can upload OR limit the number of files per upload). Luckily someone already did this, as a plugin: Upload Quota per User. It's pretty old and seems unmaintained but tested on WP 4.9.9 it works.
stackexchange-wordpress
{ "answer_score": 0, "question_score": 0, "tags": "buddypress" }
Bulk activate a theme on multisite I have a multisite and a new theme that needs to be activated across all subsites. I found an answer by fuxia from 2012 and would like to know (1) if there have been changes in WordPress since that time that would require an update to this filter, and (2) what other methods exist to accomplish this task, like using the switch_theme function or using MySQL if it is about updating an option. Reference: Changing Multisite themes on mass
Fuxia was using `update_option` in her answer and it may work, but I wouldn't recommend that - it isn't the polite way of setting a theme. So how I would approach that problem? First of all, you want to perform this action only once and for all sites. So there is no point in using any hooks. Just run the code once and then delete it. And that code should loop through all sites and set their theme: function switch_all_multisite_themes() { foreach ( get_sites() as $site ) { switch_to_blog( $site->blog_id ); switch_theme( 'theme' ); // for example 'twentyten' restore_current_blog(); } } switch_all_multisite_themes(); // run this function only once
stackexchange-wordpress
{ "answer_score": 0, "question_score": 1, "tags": "multisite, themes, database, mysql, bulk" }
XML error on sitemap.xml When I visit sitemap.xml of my WordPress website I see this error. Here is the image![enter image description here](
I look for empty lines inside every PHP files but I didn't find any but at last, I found the solution the error was due to a function which I declare in my functions.php file, the function was register_sidebar(); but I was not using it in my theme anywhere. When I removed this function in my functions.php file then sitemap.xml of my website working correctly![enter image description here](
stackexchange-wordpress
{ "answer_score": 0, "question_score": 0, "tags": "google xml sitemaps" }
Add custom html classes to gutenberg wrapper I wanna add custom classes to gutenberg wrapper. But I wanna be flexible and use the classes from inspectorinput. How can I do? Block filters don't work a that cause you can just use a special class.
* Block Filters are used to customize the class that wordpress already adds using following format `wp-block-[plugin_name]-[block-name]`. You can access that using `this.props.className`. * You can also add the additional classes using Advanced Panel which is present on right sidebar. * In the end you can use React.js component state to define custom classes (pseudo code is given below). (Create separate file for this and pass into edit method inside registerBlockType for better structuring else you can write this whole code) class Testing extends Component { constructor() { this.state = { customClasses: null } } render() { <InspectorControls> <TextControl label="Custom CSS Classes" value={ this.state.customClasses } onChange={ ( content ) => setState( { customClasses: content } ) } /> </InspectorControls> } }
stackexchange-wordpress
{ "answer_score": 0, "question_score": 0, "tags": "plugin development, block editor" }
Change the subdomain? I have setup a WordPress under a dev.example.com domain and then after developing changed the document root of the top level domain example.com to the WordPress installation. Now some links are on dev. and when I login to admin, I get redirected to dev. as well. I changed all the links manually but the language switcher still remains on dev. How do I solve this?
WordPress uses absolute links almost everywhere in its database. It means that if you want to change domain, you have to change all these links in DB. The easiest way is to export DB to SQL, find and replace all occurrences of old URL with the new one. But... This can break your DB - some things are stored as serialized objects in DB and such simple change of strings will break these objects and make them impossible to unserialize. Another way is to use tool like Interconnects Search Replace DB
stackexchange-wordpress
{ "answer_score": 0, "question_score": 1, "tags": "subdomains" }
Prevent Wordpress Automatic Logout I am using this function which is supposed to prevent wordpress from automatically logging me out. However, I am still being logged out every so often. function my_logged_in( $expirein ) { return 31556926; // 1 year in seconds } add_filter( 'auth_cookie_expiration', 'my_logged_in' ); Is there another solution to this?
As we know by default WordPress keeps logged in for `48 Hours`. If we check "Remember me" while login then it will keep login for 14 Days. If you want to set the logout timeout you can use this code as: function wpset_change_cookie_logout( $expiration, $user_id, $remember ) { if( $remember && user_can( $user_id, 'manage_options' ) ){ $expiration = 31556926; } return $expiration; } add_filter( 'auth_cookie_expiration','wpset_change_cookie_logout', 10, 3 );
stackexchange-wordpress
{ "answer_score": 1, "question_score": 0, "tags": "functions, login" }
How to Disable Right Click on wordpress Dashboard(Admin Area) Just want to know how to disable right click on dashboard(admin area) side of the wordpress.already used following code for frontend(user area). body { -webkit-user-select: none; -moz-user-select: -moz-none; -ms-user-select: none; user-select: none; }
Use the selector `.wp-admin` to make sure you are selecting only the wordpress admin area. html body.wp-admin { -webkit-user-select: none; -moz-user-select: none; -ms-user-select: none; user-select: none; } The code above will prevent the user from selecting/highlighting the page content. If you really want to disable right click, just use a simple JS code like: <script> document.oncontextmenu = new Function("alert('Right click is blocked.'); return false"); </script> References: <
stackexchange-wordpress
{ "answer_score": 0, "question_score": 0, "tags": "plugins" }
How to display only 3 main categories, separated by commas, since they are marked in the post? I want to display only 3 categories (Ex: horses, dogs, birds), names only and comma separated, in my Post, since one of them, two or all tree are marked in the post. <span><?php if ( 'in_category('horses') ) { echo "horses"; } ?></span><span><?php if ( in_category('dogs') ) { echo "dogs"; } ?></span><span><?php if ( in_category('birds') ) { echo "birds"; } ?></span>
It should be enough using a single `<span>` for all categories and add some logic.: <span><?php $categories = ['horses','dogs','birds']; $string = ""; foreach ($categories as $category){ //iterate over the categories to check if(has_category($category)) $string .= $category.", "; //if in_category add to the output } $string = trim($string); //remove extra space from end $string = rtrim($string, ','); //remove extra comma from end echo $string; //result example: <span>horses, dogs</span> ?></span>
stackexchange-wordpress
{ "answer_score": 2, "question_score": 5, "tags": "categories" }
Notification Email Address not changing I have a user that is receiving notification emails to their personal email address and we would like to have it be changed to more of public one that is used by the company. I have tried to change the Email Address field in the UI under Settings->General and when I do, the notifications are still being sent to the same email address with the Email Address field showing the new email address. Do you have any ideas of how we can get this changed?
WordPress has a plugin called WordFence. In WordFence->General Options, change the email address for alerts and this will update the notifications email. This is how I resolved my problem.
stackexchange-wordpress
{ "answer_score": 0, "question_score": 0, "tags": "email, notifications" }
Posts page not showing correct image The Wordpress site I am working on has a static front page, and all posts are sent to another page (entitled `blog`). The images on this Posts page are random pretty shots, and not in the Media collection at all. When I click on a post however, I do get the correct image in its new page. How can I either get the correct image in the Posts page, or remove these images from the Posts page entirely? Wordpress is version 5.1, and the theme is something called `Simple Business Pro`. Thank you!
If the theme you're using is this: < then... This is the code responsible for images on the blog page: <?php if (has_post_thumbnail()) { the_post_thumbnail('nimbus_722_400', array('class' => 'nimbus_722_400 img-responsive')); } else { ?> <?php if ( (simple_business_wp_get_option('fp-news-thumbs-toggle') == "1") || (simple_business_wp_get_option('fp-news-thumbs-toggle') == "") ) { ?> <img src="<?php echo get_template_directory_uri(); ?>/assets/images/preview/722x400-<?php echo rand(1,8); ?>.jpeg" class="nimbus_722_400 img-responsive" alt="<?php the_title(); ?>" /> <?php } ?> <?php } ?> As you can see, it will show post thumbnail, if it is set. And if there is no thumbnail set and some option is set to true, then it will show random image from assets. So if you're seeing some random images on the blog list, then probably you haven't set featured images for these posts.
stackexchange-wordpress
{ "answer_score": 1, "question_score": 0, "tags": "posts, images" }
Check when a setting has been changed New to WordPress plugin development and I am looking for a hook that will execute when a setting has been changed in the 'Admin Dashboard' > 'Settings pages'.
The `update_option` hook can use used to run an action when an option value has changed: function wpse_330204_option_updated( $option_name, $old_value, $new_value ) { if ( $option_name === 'name_of_option_you_want_to_check' ) { if ( $new_value !== $old_value ) { // Value has changed, run code here. } } } add_action( 'update_option', 'wpse_330204_option_updated', 10, 3 ); Just replace `name_of_option_you_want_to_check` with the actual name of the option you're looking for. _Usually_ this will be the same as the `name=""` attribute of the `<input>` or `<select>` element that's used the change the value.
stackexchange-wordpress
{ "answer_score": 0, "question_score": 0, "tags": "hooks" }
WP showing "warning: call_user_func_array()", What to do? I am currently working on designing my blog and am almost done but when I updated to 5.1 WordPress version in XAMPP, it started showing up this error message: Warning: call_user_func_array() expects parameter 1 to be a valid callback, function 'disable_embeds_rewrites' not found or invalid function name in E:\xampp\htdocs\wp\wp-includes\class-wp-hook.php on line 286 The blog theme(with custom callback for comments) I had just designed was working properly in last version of WordPress but this error started showing up just after I updated my WordPress. Please provide me some solution!
The error you're getting is showing, because somewhere on your site (your theme or one of your plugins) is registering a filter function that doesn't exist. Somewhere in your code, there will be such line (or similar to it): add_filter( 'rewrite_rules_array', 'disable_embeds_rewrites' ); It may use different hook, so it may also look like: add_filter( 'XXX', 'disable_embeds_rewrites' ); The problem is that the function `disable_embeds_rewrites` doesn't exist on your site. The easiest/quickest way to fix it is to remove the line above. PS. But you should be careful. Maybe that filter is needed on your site. So when you find it, you should contact the author of that part of code (plugin/theme) and report it as a bug.
stackexchange-wordpress
{ "answer_score": 4, "question_score": 4, "tags": "plugins, php, functions, hooks, callbacks" }
Why does paginate_links() reload the entire page? and can you make it reload only a specific div? Beginner here; apologise for any obvious mistakes. I have a post list on my homepage showing 3 posts at a time and using `paginate_links()`. When I click on page2 or next in the paginate_links(), it reloads the entire homepage(and scrolls to the top of page. Need to scroll down back to post list) and then the page2 of the post list is shown. My homepage has a lot of other content; so is there a way for `paginate_links()` to work by reloading only the post lists instead of the entire page?
`pageinate_links` is a function that retrieves paginated link for archive post pages. So yes - there are links. And links works exactly this way - if you click on it, you will go to the url that is connected with that link - so the page will get reloaded. If you want the link to cause a partial reload of only one div (or other container), you'll have to write your own code, that will: 1. Prevent the link reloading the page when clicked. 2. Send AJAX request to the server and obtain new content of that container. 3. Replace the content of container with the new content received from server.
stackexchange-wordpress
{ "answer_score": 0, "question_score": 0, "tags": "paginate links" }
How to make a "page-option" in WordPress I had made a WordPress website with my own theme. I have a navigation menu on the top of my website with dropdowns. Then you click on a page in this menu, I want you to navigate to a page, where there is a specific widget with a navigation... But, on another dropdown page I want another widget. So, my question is: "How can I make an "option" to choose the right widget to a specific page?". I hope someone can help! - thanks.
You can define a specific page template for the specific widget then you can select template page as on your navigation menu. <?php /* Template Name: page one */ get_header(); ?> <div class="main-wrap "> <?php if (is_active_sidebar( "widgetName" )) { dynamic_sidebar( "widgetName" ); } ?> </div> <?php get_footer(); ?>
stackexchange-wordpress
{ "answer_score": 0, "question_score": 0, "tags": "php, widgets" }
How to get full native language instead of iso? I am not using WPML or Polylang, but multisite to create multiple languages. The code below is used to make a language switcher, but I want a second menu with the full language name for a different menu (i.e. EN should be English, FR - Français, DE - Deutsch). Wordpress has the native names stored (because when selecting a language you get a list with the native language name), but how can I access this to use? $languages = get_available_languages(); foreach ($languages as $item) { $iso = substr($item, 0, 2); echo '<li>'. $iso .'</li>'; }
I'm almost sure that you can use `locale_get_primary_language` function for that. echo locale_get_primary_language( $item ); Maybe it'll need some tweaking, because I'm not sure if formats will match (for example you may have to change ' _' to '_ ' or change it to lower/upper-case).
stackexchange-wordpress
{ "answer_score": 0, "question_score": 0, "tags": "theme development, multisite, multi language" }
Invalid key on activation and password reset I am in a pickle now, about to release a Wordpress-based app and I can't get the registration complete because password set/reset key is **sometimes** invalid. I say sometimes because when the user is registered, he gets link to set the password, and that is always invalid. Then he is asked to enter his username to reset the password and a new email is sent. That link is also invalid, however, if he requests a new password reset email again, then the link is valid. The problem seems to be the key generated. When they key is clean of symbols, it works, example: ` When the key is with symbols, it gets denied, example: ` I disabled all plugins and it acts the same way. No caching plugins installed. What could be happening here? Please help! **Edit:** I repĺicated this behavior again to make sure, and this time it took 4 tries. So I am guessing that if you keep trying to get a clean key, it works. Why would this be happening?
Problem solved! I had a filter hooked onto `random_password` filter to generate passwords with custom rules and `get_password_reset_key` uses the function `wp_generate_password` to generate the key, and that is why I was getting the behavior I was getting. Allz I had to do was to remove my filter from it, and bada bing bada boom, it works.
stackexchange-wordpress
{ "answer_score": 1, "question_score": 1, "tags": "user registration, authentication, password" }
media sideload image and Google Content I'm trying to take a pages og:image from a URL and add it to the media library and post meta. Works great until I hit a google user content url. $image_url = " media_sideload_image( $image_url, $post_id, '', 'src' ); Results in "not valid image url". I would guess it has to do with how the google image url for og:image doesn't have any type of image extension on it. Is there a work around for this?
I did a little searching and it looks like _maybe_ you can fix it by appending `?.jpg` to the end of the URL. According to this guide that gets around most URL parsers
stackexchange-wordpress
{ "answer_score": 1, "question_score": 1, "tags": "images, uploads, google" }
get_current_site() is undefined I get the error `Fatal error: Uncaught Error: Call to undefined function get_current_site() in XXXXXXXX` Why is this happening? Do I need to load something before I can use that function? Is my Installation wrong? Thanks in advance PS: my Code (if you need it) $f = function () { ob_start(); var_dump(get_current_site()); file_put_contents(__DIR__ . '/dump.html', ob_get_clean()); return; // I actually want to put styles here later, which change with every page }; add_action('wp_enqueue_scripts', $f);
`get_current_site()` is a function for getting the current Multisite Network. As with other multisite-related functions, it is not available to use if your site is not configured as a multisite network. ~~I can't tell from your code what you're attempting to use the function for, so I can't offer a suggestion for what to use instead.~~ If you want to check if you're on a specific page you can use `is_page()` along with the slug of ID if the page you're checking for: if ( is_page( 'about-us' ) ) { } if ( is_page( 5 ) ) { }
stackexchange-wordpress
{ "answer_score": 1, "question_score": 0, "tags": "php, functions" }
How can I load the css and jquery explicitly for the login screen To avoid conflict I need to load the CSS and jquery explicitly for the login screen only and neither an admin nor on the frontend. Given that I have a custom login screen.
You can load scripts and styles on the login page using the `login_enqueue_scripts` hook. You can use the same enqueue functions for scripts and styles that you'd use for other pages but they'll only load on the login page: function wpse_330353_login_scripts() { wp_enqueue_script( 'handle', '//example.com/url/to/script.js' ); wp_enqueue_style( 'handle', '//example.com/url/to/style.css' ); } add_action( 'login_enqueue_scripts', 'wpse_330353_login_scripts' ); None of this would be affected by changing the URL of the login page.
stackexchange-wordpress
{ "answer_score": 1, "question_score": 0, "tags": "plugins" }
Two problems on my WordPress installation First problem is I can't scroll on creation post page, same with disabled all plugins. Second problem is I have already an update notification in menu but no update on update page. ![enter image description here](
Without further info, hard to say. But I would * update WP again (even if you already did, just to make sure it is fully updated) * change to one of the 'twenty' themes (you can do that by temporarily renaming the current theme's file folder). Since you state that you disabled all plugins (but not how; I assume that you renamed the plugin folder?) it would seem that the plugins are not the problem. That's why I suspect the theme - and re-doing the WP update couldn't hurt.
stackexchange-wordpress
{ "answer_score": 0, "question_score": 1, "tags": "plugins, posts, updates" }
Is it possible to access plugin data from a custom feed template? I'm trying to use `current_user_can` in a custom feed template (created using `add_feed`) to check if they have a particular Memberpress membership plan in order to access the feed, but while I can get other user data (e.g. `$current_user->user_login` outputs the username), I can't use the plugin function. At the moment, instead of showing the feed, I'm just echoing some test content, as follows: if( current_user_can( 'mepr-active', 'memberships:1,2' ) ) { echo 'Hi ' . $current_user->user_login . '! You are a member'; } else { echo 'Hi ' . $current_user->user_login . '! You <strong>not</strong> a member'; } I'm guessing this is something to do with the order WordPress loads things. Could someone confirm? Is there any way around this? (I can get it working if I add the same code to a page template within the theme.) Thanks
The solution, for anyone else interested, was to clear cookies and the cache: clean_user_cache($current_user->ID); wp_clear_auth_cookie(); wp_set_current_user($current_user->ID); wp_set_auth_cookie($current_user->ID, true, false); update_user_caches($current_user); if( current_user_can( 'mepr-active', 'memberships:1,2' ) ) { echo 'Hi ' . $current_user->user_login . '! You are a member'; } else { echo 'Hi ' . $current_user->user_login . '! You <strong>not</strong> a member'; }
stackexchange-wordpress
{ "answer_score": 1, "question_score": 0, "tags": "templates, users, rss" }
WP Query by Gutenberg block and get its attribute I need to fetch on the front page youtube video from the latest post where was used gutenberg youtube block. I guess I need: 1) query such posts 2) extract the youtube URL from the block Is there a way how to do that?
After hours of googling I came up with following solution. Maybe once will help to someone. 1) query post where is used gutenberg youtube block: $args = array( 'post_type' => 'post', 'post_status' => 'publish', 's' => 'core-embed/youtube', 'posts_per_page' => 1 ); $query = new WP_Query($args); 2) extract the URL from youtube block of the post $post_id = 117; $post = get_post($post_id); $blocks = parse_blocks( $post->post_content ); function findYoutubeBlock(array $blocks) { return $blocks['blockName'] == 'core-embed/youtube'; } if (has_block('core-embed/youtube', $post_id)) { $youtube_block = reset(array_filter($blocks, 'findYoutubeBlock')); $youtube_url = $youtube_block['attrs']['url']; }
stackexchange-wordpress
{ "answer_score": 3, "question_score": 1, "tags": "wp query, block editor, embed" }
Why submenu item's background color is not changing by css? I am developing child theme based on Accelerate by ThemeGrill. I am trying to change submenu item's background color. However it is not affacted by any selector. I have tried to add following to Additional CSS options: *{ color: #00df00 !important; background-color: #50df50 !important; background-image: none !important; } This results in every item in the page to be green except submenu's backgroud which is still gray. However text of the submenu items were changed, so the submenu items are partialy affected by this css. Why is the background color of submenu items not changing?
CSS is a game of competing priorities. When two rules conflict, whichever one has the higher specificity wins. If you have these rules and something is not affected by it, then something else has a higher specificity. Since you have specified the !important tag, whatever is trumping you is also using the !important tag. Then it is trumping you by also having a higher specificity in another way (or even just by coming after yours). You need to inspect the element and find out the source of your competition, then write a rule to trump it. The difficulty in trumping !important tags is the precise reason they are absolutely not recommended. No one else can diagnose this further without seeing the actual page where it is happening (since you don't know where the other style rules are coming from).
stackexchange-wordpress
{ "answer_score": 1, "question_score": 0, "tags": "themes, css, child theme" }
Gutenberg get block name I'm using a filter in the Block API to add a class name to a block's wrapper. I have to add the class name to a specific block, not all blocks. I tried: const addClassName = createHigherOrderComponent( ( BlockListBlock ) => { return ( props, blockType ) => { if ( blockType.name === 'myplugin/myblock' ) { return <BlockListBlock { ...props } className="test" />; } return <BlockListBlock { ...props } /> } }, 'addClassName' ); wp.hooks.addFilter( 'editor.BlockListBlock', 'myplugin/add-class-name', addClassName ); The issue: `blockType.name` returns undefined. I also tried `getBlockType.name` and it also returns undefined. I also tried getting the block name of core blocks. For example `core/columns`.
From the props object we can get the block information. The object contains the `name` property you are looking for; this would be the code: const addClassName = createHigherOrderComponent(BlockListBlock => { return props => { if (props.name === "myplugin/myblock") { return <BlockListBlock {...props} className="test" />; } return <BlockListBlock {...props} />; }; }, "addClassName"); wp.hooks.addFilter( "editor.BlockListBlock", "myplugin/add-class-name", addClassName );
stackexchange-wordpress
{ "answer_score": 2, "question_score": 1, "tags": "block editor" }
How to put Stripe first, PayPal second on the checkout page? On our checkout page we have PayPal first, after that Stripe. How to put Stripe first, PayPal second on checkout page? ![o](
In your admin panel, go to `Woocommerce` > `Settings` > `Payments` tab > and drag the payment methods in the order you want.
stackexchange-wordpress
{ "answer_score": 2, "question_score": 0, "tags": "woocommerce offtopic, paypal" }
Display html code, not the tags I am using a theme and I want to modify it in order to use html code in a text field. This is the part of the code that renders this field: do_shortcode( wpautop( esc_html( $sectionData['left-content'] ) ) ) I want to modify it in order to display html code properly, but it keeps rendering the tags and not the formatted text. I want to display **this** but it displays `<b>this</b>`. How I can modify it?
You need to remove the `esc_html()`. The whole purpose of that function is to prevent text being interpreted as HTML. do_shortcode( wpautop( $sectionData['left-content'] ) );
stackexchange-wordpress
{ "answer_score": 0, "question_score": 0, "tags": "html" }
Meta_query is not working on Elementor Custom Query Filter I’m following this tutorial to create a custom query filter. I would like to filter by a metadata created by ACF (Advanced Custom Field), but it seems not working for me. My code is like this: add_action('elementor_pro/posts/query/my_custom_qurery', function($query) { $searchStr = get_search_query(); $meta_query = [ 'key' => 'codigo_de_barra', 'value' => $searchStr, 'compare' => '=', ]; $query->set('meta_query', $meta_query); $query->set('post_type', 'produto'); }); I’m using the widget “Posts” to display the results and I’m sure that I have set the custom query to Custom ID field, because the post_type is affecting results when I change it. Why meta_query is not working?
Meta query is an array containing arrays and not only one array (you can set multiple queries). So it should be: $meta_query = [ [ 'key' => 'codigo_de_barra', 'value' => $searchStr, 'compare' => '=', ] ];
stackexchange-wordpress
{ "answer_score": 1, "question_score": 1, "tags": "custom field" }
Woocommerce cart table too wide I am developing a custom theme from scratch and I am using woocommerce to build the shop. The problem is that on the cart page, the cart table ( with all the products added to cart) is too wide and is scrollable. The product images are small but each column is very wide. I tried it on several different themes and the result is the same. I might be wrong but I don't think that this it the default behaviour of it. I want to make it fit the screen without being scrollable.
What you see if default Woocommerce. To override the cart page, copy the WooCommerce template file to your theme like so: woocommerce/templates/cart/cart.php to --> yourtheme/woocommerce/cart/cart.php and modify it in your theme.
stackexchange-wordpress
{ "answer_score": 0, "question_score": 0, "tags": "woocommerce offtopic" }
Failed opening required I am new in wordpress development. Tried include a selfwritten php-file into **htdocs/wp-content/plugins/abc/abc.php** IDE sugesting me to use: `require_once '../WPNonce/WPNonce.php';` ![IDE Suggestion of file path]( but WordPress contradicts when opening in webbrowser: `Fatal error: require_once(): Failed opening required '../WPNonce/WPNonce.php'` How could i include this php-file (its a class inside)?
WordPress includes many functions for determining paths and URLs to files or directories within plugins, themes, and WordPress itself. $plugin_dir = plugin_dir_path( __DIR__ ); // wp-content/plugins/ require_once($plugin_dir.'WPNonce/WPNonce.php'); While using `plugin_dir_path()`, keep in mind that **the “plugin” part of the name is misleading** – it can be used for any file, and **will not return the directory of a plugin unless you call it within a file in the plugin’s base directory.** or alternatively, you can also use WordPress constant `WP_PLUGIN_DIR ` require_once(WP_PLUGIN_DIR.'/WPNonce/WPNonce.php'); I hope this helps.
stackexchange-wordpress
{ "answer_score": 1, "question_score": 0, "tags": "filesystem" }
Attaching author tag to the comment I have found how to highlight comments made by author of the post. However, could not achieve to attach simple text saying this is author for each comment replied by the author of the post.
you can compare user_id to the author id, an then add your text. global $post; if ( $comment->user_id === $post->post_author ) { echo 'Author'; }
stackexchange-wordpress
{ "answer_score": 0, "question_score": 0, "tags": "comments, author" }