INSTRUCTION
stringlengths
11
999
RESPONSE
stringlengths
0
999
SOURCE
stringlengths
16
38
METADATA
dict
Show some menu sub items as dropdown under a menu item I have made a custom wordpress menu - function my_custom_menu_item($items, $args) { if(is_user_logged_in() && $args->theme_location == 'primary') { $user=wp_get_current_user(); $name=$user->display_name; $items .= '<li><a href="">'.$name.'</a></li>'; $items .= '<li><a href="/my-profile">My Profile</a></li>'; $items .= '<li><a href="/my-posts">My Posts</a></li>'; } return $items; } add_filter( 'wp_nav_menu_items', 'my_custom_menu_item', 10, 2); It shows 'name of the logged in user', 'My Profile', 'My Posts' side by side in a flat structutre. I want 'My Profile' and 'My Posts' to show as dropdown under 'name of the logged in user'. How do I do that?
Remove the first closing `</li>` and wrap the sub-items inside `<ul></ul>`, then close the parent `<li>`. For Example: function my_custom_menu_item($items, $args) { if(is_user_logged_in() && $args->theme_location == 'primary') { $user=wp_get_current_user(); $name=$user->display_name; $items .= '<li><a href="">'.$name.'</a>'; $items .= '<ul>'; $items .= '<li><a href="/my-profile">My Profile</a></li>'; $items .= '<li><a href="/my-posts">My Posts</a></li>'; $items .= '<ul>'; $items .= '</li>'; } return $items; } add_filter( 'wp_nav_menu_items', 'my_custom_menu_item', 10, 2);
stackexchange-wordpress
{ "answer_score": 1, "question_score": 0, "tags": "functions, menus, theme options" }
Can `<style>` and `<script>` tags be used in the HTML editor? I understand this is so stupid, because absolutely there should be an answer out there, but I can't find it myself. In short, can you use `<style>` and `<script>` tags in the HTML editor, without any plugin or touching the style.css file? I am an author of a blog I don't own, and I would like to add custom styles on my articles. I try it and it seems that it doesn't work, but I would like to have a definite answer.
**Mostly no** , but you shouldn't do that anyway. The exception, is if your user has the `unfiltered_html` capability, which is a dangerous power to have. Users that have this are admins on a single site install, or a super admin on a multisite install. But, there are major security downside to putting script and style tags directly into articles. For CSS, it's unnecessary, the customizer has a built in CSS editor. If your theme is built correctly, the body tag and main article/post tag will have IDs and classes you can use to target specific posts For Javascript, this should be in the theme or a plugin. Entering javascript into the database opens up a security can of worms. If you must do it, do it via a custom field and some code, or a plugin. Don't do it via post content
stackexchange-wordpress
{ "answer_score": 3, "question_score": 1, "tags": "css, javascript, html editor" }
Auto redirect to different web page I am trying to create example.com/abc page for my site but I am getting permalink as example.com/abc-3. When I am entering example.com/abc it is redirecting me to example.com//wp-content/uploads/2018/09/on-page-seo.png Please help me out.
If you are getting a permalink that is `abc-3` while you are entering `abc` that often suggests that somewhere the slug is already being used. Perhaps `abc` is already used as a category, or a page. Or perhaps it was previously created and deleted and it is still in the trash. Make sure you delete it even from the trash so that that slug can be re-used.
stackexchange-wordpress
{ "answer_score": 0, "question_score": 0, "tags": "redirect" }
$wpbd->insert() does not insert user data I am having trouble inserting logged-in user data, using the 'user_register' hook. The following code inserts a row in the database, but only inserts the 'email' column. function nuevoPostulante() { global $wpdb; $tablaPostulante = $wpdb->prefix . 'postulante'; $current_user = wp_get_current_user(); $wpdb->insert( $tablaPostulante, array( 'dni' => $current_user->user_login, 'nombre' => $current_user->display_name, 'email' => '[email protected]', ) ); } add_action('user_register', 'nuevoPostulante'); Columns with values ​​taken from '$ current_user' are empy, the insert do not seem to take data from the array. I think it's a scope problem, I still don't understand how to fix it. Somebody could help me? Thank you!
user_register action allows you to access data for a new user immediately after they are added to the database. The user id is passed to hook as an argument. So you wish to insert record for user when user register you can modify your code like follows: add_action( 'user_register', 'nuevoPostulante', 10, 1 ); function nuevoPostulante( $user_id ) { global $wpdb; $tablaPostulante = $wpdb->prefix . 'postulante'; $current_user = get_user_by( 'ID', $user_id ); // You can use get_userdata( $user_id ) instead of get_user_by() both can be work perfectly suite your requirement. $wpdb->insert( $tablaPostulante, array( 'dni' => $current_user->user_login, 'nombre' => $current_user->display_name, 'email' => '[email protected]', ) ); }
stackexchange-wordpress
{ "answer_score": 0, "question_score": 0, "tags": "wpdb" }
Run a security scan on WordPress site that has .htaccess password Firstly, I don't know the correct term for what this password thing is. I think it's just a line in .htaccess, that prevents bots or unauthorized access to a staging environment, but it also breaks some other functionality from time to time. It's possible the password is not in .htaccess. I don't have access to it, and I cannot disable it. I've tried 2 popular security plugins to run a scan on my site (am I allowed to say their names?), but they run into errors such as: "The scan has failed to start. This is often because the site either cannot make outbound requests or is blocked from connecting to itself." "SiteCheck error: Unable to properly scan your site. 401 Unauthorized" Is there another "tool" that will run a scan without me disabling the password? (am I allowed to ask for suggestions on WordPress "tools"?)
The parent directory (which I don't have access to) uses htpasswd, but I can override this for my directory only by adding Satisfy Any to .htaccess. This fixes the issues I was having. I'm ok with disabling the authentication temporarily to run a scan and turning it back on afterwards. More info on disabling htpasswd here: <
stackexchange-wordpress
{ "answer_score": -1, "question_score": -1, "tags": "security" }
Trying to reload page with update_option_{$option} hook causing infinite reload How can I reload the page after this option is updated? What I'm trying below is causing an infinite page reload loop. I've also tried add if($old_value !== $) check but still no luck. add_action( 'update_option_kdc-site-functions', 'kdc_reload_admin', 10, 2 ); /** * Reload admin page after settings page is saved. */ function kdc_reload_admin( $old_value, $value ) { ?> <script type="text/javascript"> document.location.reload(true); </script> <?php }
The reason this was happening, is metabox.io for some reason triggers a page refresh before saving the option. This meant that after the page refresh, the new options did not have time to take effect. My workaround for now is to use header("refresh:0") which accomplishes what I was trying to do in my original post but without causing a refresh loop like the javascript refresh method. Simply forces another page refresh after the option is successfully saved.
stackexchange-wordpress
{ "answer_score": 0, "question_score": 0, "tags": "php" }
Stop wordpress from requesting external jquery from googleapi Instead of using external jquery hosted on google i would like to use a local copy. I am able to tell wp to use the local version, however, I seem to be unable to stop wp requesting the google hosted one. when I do (in functions.php): `function register_local_juery() { wp_deregister_script('jquery'); wp_enqueue_script('jquery', 'url/to/local/jquery', array(), null, true); } add_action('wp_enqueue_scripts', 'register_local_juery');` The result of this is that wp includes both. The local and external. How can I stop wp from using the external source? In times of increasing awareness with privacy, shouldn't that be a kind of more obvious option? Is it possible that the call to googleapi is initiated by any plugin I have installed? Or do they always use the one registered with wp theme?
WordPress _doesn't_ use externally hosted jQuery. In fact, as far as I'm aware, WordPress core does not register _any_ externally hosted scripts. WordPress bundles its own version of jQuery, and you can enqueue the bundled version by just enqueueing the handle `jquery`: wp_enqueue_script( 'jquery' ); Or by specifying `'jquery'` as a dependency: wp_enqueue_script( 'my-script', '/path/to/my-script.js', [ 'jquery' ] ); If you enqueue jQuery like that, but it's still loading an externally hosted version, then your theme or a plugin is either loading its own version separately, or has re-registered `jquery` with an external version. The easiest way to find the culprit is to deactivate plugins, checking your site after each one, to see if the correct version is loading.
stackexchange-wordpress
{ "answer_score": 1, "question_score": 0, "tags": "plugins, jquery, google" }
Add code to the header of posts by particular author I want to add CSS code to the header of all the posts by a particular author. I tried the following solution: function hide_author_box() { if (is_author('ritesh')) { ?> <style> .author-box { display: none; } </style> <?php } } But it doesn't work. How do I fix it?
`is_author()` is _not_ for determining current user, it checks whether the Author archive page is in display or not. Your call would be to use `wp_get_current_user()` or `get_current_user_id()` (if you are comfortable with user ID) or any similar function WP have. ### Example of using `wp_get_current_user()` <?php $current_user = wp_get_current_user(); if ( 'ritesh' === $current_user->user_login ) { // do something }
stackexchange-wordpress
{ "answer_score": 0, "question_score": 0, "tags": "php, wp query, conditional tags" }
retrieve current user meta data (custom fields included) I use "User Registration" plugin to create a registration form. Once the user has registered and logged in, I need to retrieve inside "Function.php" all his data that he completed in the registration form. I already tested `wp_get_current_user()` but it only return default fields...
Have you tried `get_user_meta($user_id, $key, $single);`? <
stackexchange-wordpress
{ "answer_score": 1, "question_score": 1, "tags": "functions" }
Use composer to load custom classes I want to use composer to load my custom classes inside my plugin. I've tried to use it but without success. Is possible to use compose for the plugin develop to manage custom classes used inside it? Can anyone point me into the roght direction?
Without more context from you, I can only assume and show you what I have done that works for me using PSR4 Autoloading. ### Example: Assuming that all my custom class directories and files is in **./inc** folder In your composer.json, add this "autoload": { "psr-4": { "Inc\\": "./inc" } } **Inc** is the vendor name of your application, use this for namspacing files inside your **inc** directory like `namespace Inc/Api;` **./inc** is the directory(with all the class files or nested directory) you want to autoload. Next, do this in your terminal to generate the vendor directory & autoload the files. composer dump-autoload Lastly, require the the autoloading by adding this to your plugin file _eg. my-awesome-plugin.php_ if (file_exists(dirname(__FILE__) . '/vendor/autoload.php')) { require_once dirname(__FILE__) . '/vendor/autoload.php'; }
stackexchange-wordpress
{ "answer_score": 1, "question_score": 1, "tags": "php, plugin development, composer" }
Enqueued stylesheet appends query string, causing "SyntaxError: Invalid or unexpected token" function renderProductPageUi() { wp_enqueue_style('stylesheetHandle', plugins_url('pluginName/semantic/dist/semantic.css')); require_once ('templates/offerBox.php'); } add_action('woocommerce_after_add_to_cart_button', 'renderProductPageUi'); In Chrome browser I see this red console error: SyntaxError: Invalid or unexpected token Notice the `?ver=5.1.1` at the end. I vaguely recall this being a wordpress behavior. Is that what is causing the console error? If so how should it be corrected?
To elaborate on my comment: `SyntaxError: Invalid or unexpected token` is not an error that you will ever see related to CSS. This is a _JavaScript_ error that occurs when there's a syntax error in some JavaScript. If you see this error and it's occurring in a CSS file, then it means that you have improperly loaded a CSS file in `<script>` tag, which means the browser will try to parse the CSS as JavaScript, which will inevitably produce a syntax error, because CSS is not valid JavaScript. This will happen in WordPress if you try to use `wp_enqueue_script()` on a CSS file. Make sure you only use `wp_enqueue_script()` for JavaScript files, and `wp_enqueue_style()` for CSS files.
stackexchange-wordpress
{ "answer_score": 2, "question_score": 0, "tags": "errors, wp enqueue style" }
How To Post WordPress Custom Post Types to Twitter via IFTTT I have my wordpress site. Which has the normal "post" and a custom post type "download", I Currently use IFTTT, (If This Then That Service) to post my wordpress posts to Twitter. The IFTTT recipe works perfectly for my posts, and tweets as soon as I publish any post. You can check my site < and my twitter account is < The problem is that, this works only for normal wordpress posts. I searched IFTTT for applets to include custom post types, that didn't work, and i can not find a solution on stack exchange also. How can i use IFTTT, to tweet any new post of post type 'download' I love IFTTT, and i don't want any plugins that slow down my site. So please provide me with the code, that ensures that my IFTTT applet is triggered for this custom post type also.
IFTTT works from RSS feed, simply including your post in wordpress RSS feed can do the trick... function add_cpt_to_loop_and_feed( $query ) { if ( is_home() && $query->is_main_query() || is_feed() ) $query->set( 'post_type', array( 'post', 'download' ) ); return $query; }
stackexchange-wordpress
{ "answer_score": 1, "question_score": 0, "tags": "custom post types, plugins, php, xml rpc, social sharing" }
REST API: No route was found matching the URL and request method I'm having issues adding a custom REST API route to Wordpress. Using my own plugin, i've registered the route as followed: add_action( 'rest_api_init', function() { register_rest_route( $namespace, 'handler_mijnenergie', array( 'methods' => '\WP_REST_Server::CREATABLE ', 'callback' => [ $this, 'handle_energie_data' ] ), false ); } ); When calling the namespace "/wp-json/watz/v1" I get a correct response in Postman that the route is shown. ![enter image description here]( However, when i try to access the route request directly, i get thrown a 404 error. So far I've tried: * Rewriting the permalinks * Using standard Wordpress .htaccess * Disabling plugins * Changing method/namespace & request * Testing other plugin routes like Yoast or Contact Form 7 (they work) Any idea what could be causing the issue here and what I need to alter to get this working?
It's because of how you've defined the accepted methods: 'methods' => '\WP_REST_Server::CREATABLE ', You shouldn't have quotes around it. `WP_REST_Server::CREATABLE` is a string that equals `'POST'`, but by putting quotes around it you're literally setting the method as `'\WP_REST_Server::CREATABLE'`, which is not a valid HTTP method. You can see this in the response to the namespace endpoint. Set it like this: 'methods' => WP_REST_Server::CREATABLE Or, if your file is using a PHP namespace, like this: 'methods' => \WP_REST_Server::CREATABLE Or add this to the top of the file: use WP_REST_Server; Then make sure that when you're accessing the route directly, that you're using the correct method. If you're using `WP_REST_Server::CREATABLE` then the endpoint will only respond to `POST` requests, so `GET` requests will return a 404, which includes when you access it via the browser.
stackexchange-wordpress
{ "answer_score": 5, "question_score": 3, "tags": "404 error, rest api, routing" }
How to Disable Auto Executing Script in A Particular Page Only I used this < plugin to add an opt-in form on every page. Now I want to disable a page to auto-insert this form and make a landing page. I'll use a different opt-in form for that landing page, how can I do that? Thanks Note: that plugin does not support except page.
I found a plugin which is helping me to solve this issue. The plugin link is: <
stackexchange-wordpress
{ "answer_score": 0, "question_score": 0, "tags": "plugins, pages" }
Getting users by specific capability, not role Is there a way to use the get_users() function, or maybe another way, to retrieve all users of a custom user capability? For example, I have given a select number of users the capability of 'team_member', which allows a user to access areas non team members cannot. Due to the nature of the site, simply creating a new role is not an option. I'm also not able to just add the capability to an already registered role. I assumed there would be a way to do this using get_users, but there doesn't seem to be. Unless I'm wrong? $args = array( 'role' => 'team_member' ); get_users( $args ); If there isn't a way to get users from custom cap, my next idea is to not use custom capabilities but instead insert the same key in a user's usermeta. This will then at least allow me to include a meta_query in the get_user $args.
I gave it a test run. First, I added a custom capability to a specific user, using following code $user = new WP_User( $user_id ); $user->add_cap( 'team_member' ); Luckily, this user can be retrieved using below code, as you suggested $args = array( 'role' => 'team_member' ); get_users( $args ); Which implicitly work like below $args = array ( 'meta_query' => array( array( 'key' => 'wp_capabilities', 'value' => '%team_member%', 'compare' => 'LIKE' ), ) ); $wp_user_query = new WP_User_Query( $args ); Reference: WP_User_Query
stackexchange-wordpress
{ "answer_score": 2, "question_score": 1, "tags": "users, user roles, capabilities, wp user query" }
Cron job shedules replace? I was watching this: Wp_Schedule_Event every day at specific time and im wondering if I do the following will it replace all my schedules? function myprefix_custom_cron_schedule( $schedules ) { $schedules['every_six_hours'] = array( 'interval' => 21600, // Every 6 hours 'display' => __( 'Every 6 hours' ), ); return $schedules; } add_filter( 'cron_schedules', 'myprefix_custom_cron_schedule' ); I have more cron jobs running but if I do this will it replace the timer? For example, I have 1 running 1 time every hour, will it be replaced? Just wondering if it will mess up the `cron_shedules`.
This won't affect your existing scheduled Cron events, as they already have a schedule interval set. It will only add a new custom schedule interval that will be available for new ones. So long as you are adding to the `$schedules` array and returning it (which you are) then it will all be fine.
stackexchange-wordpress
{ "answer_score": 0, "question_score": 0, "tags": "plugins, php, customization, cron" }
Style reset password page? /wp-login.php?action=rp I cannot figure out how to style the reset password page. And I do not mean the page where you request it, I mean the page you are shown when you click the link in the email to set your new password. The URL is `/wp-login.php?action=rp` And looks like this ![]( And the confirmation page: ![]( How do I load my custom styles for these?
You should use login_enqueue_scripts, you can load styles or scripts with it. Example: function login_styles() { wp_enqueue_style( 'loginCSS', '/my-styles.css', false ); } add_action( 'login_enqueue_scripts', 'login_styles', 10 );
stackexchange-wordpress
{ "answer_score": 3, "question_score": 3, "tags": "customization, wp enqueue style" }
Link To Child Category For A Post I'm trying to display a link to just the child category on a Wordpress post. For instance if the category for a post is parent > child I want to show a link to just the child category page. I'm using code from here: Name of last category level for a post It works perfectly but just prints the child category, how do I go about making it a link tot he child category? $allCat = get_the_category(); $lastCat = array_reverse($allCat); echo $lastCat[0]->name;
You can use get_category_link() for that: $allCat = get_the_category(); if( ! empty( $allCat ) ){ $lastCat = array_reverse( $allCat ); $last_cat_link = get_category_link( $lastCat[0] ); if( ! is_wp_error( $last_cat_link ) ){ echo '<a href="' . $last_cat_link . '">' . $lastCat[0]->name . '</a>'; } } <
stackexchange-wordpress
{ "answer_score": 1, "question_score": 0, "tags": "categories, links, array" }
Is There A Plugin to Create WP Multisite Installs programatically So I created a wordpress multi-site and I want to be able to create multiple sites in the network programmatically. My subscription service has an API so I can create username and passwords on the fly when they sign up I just need to be able to create the site with some defaults when they sign up. Also if there is a good Admin tool to manage these sites that would be awesome.
There are several really good plugins, like "MultiSite Clone Duplicator", that allow you to clone/duplicate and existing site. I run a multisite installation with over 200 sites. We started by creating a basic "template" site, which held all the basic/default settings we wanted for every new site. Then, we just clone that each time we want a new site. The newly created site can then have new administrators and editors created. Our team is already setup as super admins, and (thanks to cloning) local site admins for every site. For more admin/management tools, you might refer to this article. It has a list of plugins (some I've used, some not) to help you manage multisite networks easier. Hope this is what you were looking for!
stackexchange-wordpress
{ "answer_score": 1, "question_score": 0, "tags": "multisite, wp admin, admin, rest api, api" }
Convert multiple image blocks to gallery block in Gutenberg? Its easy to convert a gallery block into multiple image blocks. But how do I do the reverse? I have several older posts with a dozen or so images sequentially. I would like to display these all in a gallery block without searching the media library one at a time to rebuild it.
I know this has been a while, but I found this page looking for the same answer. Once I discovered the solution, I thought I would share it here to help you or someone in the future. Once you convert the classic to blocks, you can multi select the images, and then the convert button allows you to convert to a gallery. I noticed mine stayed at thumbnail until I go to edit the gallery. I don't make any changes just save gallery, and then the images don't default to the thumbnail size any longer. This part may vary by user depending on how the images were initially added. Hope this helps.
stackexchange-wordpress
{ "answer_score": 0, "question_score": 0, "tags": "images, gallery, block editor" }
How Meta Data is different from Custom Fields of POST/PAGE in WordPress I am really looking forward to have a clear picture of **Why Meta data is being used for the Posts/Pages?** I have always been wondering on how Meta data is different from the `Custom Fields` of Posts. I have read about the Meta-Data on certain websites, and got to know that the definition is quite confusing. This goes like: > Meta data are used to add some more details or data to the posts/pages. Now, what I feel, is when we add fields to the post type, we are also creating the same details/extra information for the same. Please give some more details in a brief way so that I can understand the difference between **Meta data and Custom Fields** in a POST/PAGE.
A custom field is a visible form element where users can add information. It's presentation. Meta data are data stored in one of the meta tables for posts, users, terms and so on. The content of a custom field can be stored as meta data, in a separate table, a text file, on a remote site … wherever you want it. In most cases, custom fields for posts are stored as post meta data.
stackexchange-wordpress
{ "answer_score": 1, "question_score": 1, "tags": "custom field, metabox" }
How do I Name a WP page in the New(ish) Block Editor? I'm building a custom theme and it's my first time doing this with the new(ish) block editor. Can I ask - where on earth to add the page title in the backend block editor? In the old editor you just added it at the top of the page. I've added a 'title' but this is just the h2 default title, not the page title/name. Image-1 shows the page being nameless, Image-2 shows the H2 title. ![enter image description here]( ![enter image description here]( Many thanks, Emily
Click on "Add title" and it should bring up a text input.
stackexchange-wordpress
{ "answer_score": 2, "question_score": 0, "tags": "pages, title" }
Is It Possible to Upload Certain Attachment Files To A Remote Server ### My Situation I'm developing a book-store WordPress website where you can purchase and download books in PDF format. I don't want to use the local space for file storage (the host provider offers cheaper solutions for "download servers"). * * * ### What I want to achieve Every time my client tries to upload a new book to the website through media library upload feature, WordPress can detect that it's a PDF file and automatically upload it to the _Download Server_ and save that URL (e.g. books.mywebsite.com/books/novel/the-new-book.pdf ) into the database along with it's attachment data.
The first thing I can think of is about using APIs from also popular hosting services like **Dropbox**. If you look at the documents it’s pretty easy to upload, list and delete files. I’m pretty sure you can do the same with other dozens of similar services. The WP API will do the _REST_ (LOL)... Read more here.
stackexchange-wordpress
{ "answer_score": 0, "question_score": 1, "tags": "uploads, media library, cdn, pdf" }
How to return html as a string from php for WordPress How to return html as a string from php for WordPress function play_audio($atts){ $a = shortcode_atts( array( 'url' => '' ), $atts ); wp_enqueue_script('player'); wp_enqueue_script('play_script'); wp_enqueue_style('progress_bar'); return '<div class="mediPlayer"> <audio class="listen" preload="none" data-size="250" src=" . $a[url] . "></audio> </div> </div>'; } add_shortcode( 'playaudio', 'play_audio' ); `src=" . $a[url] . ">` I'm confuse with this part its not return url
You are missing multiple single quotes around `$a[url]`, so after `src="` there should be a ' and after `$a[url]` there should be another single quote, and you also need to quote the array key, so the whole return line should be return '<audio class="listen" preload="none" data-size="250" src="' . $a['url'] . '"></audio></div></div>';
stackexchange-wordpress
{ "answer_score": 0, "question_score": 0, "tags": "php, plugin development, shortcode, html" }
Add a Different CSS Class Into The Body Tag of Different WP Pages I'm transferring a 20 page static HTML site to a custom Wordpress Theme. On each page of the static site the `body` tag has a custom CSS class i.e. 'banking-page'. I know that WP generates page id classes in the body tag to represent the individual pages (i.e. .page-id-27), but in terms of readability (and transferability), is it possible to add a bit of php onto each page which will insert a specific class into the body tag CSS for that particular page? Using the `body_class()` function won't do it because it will show on every page. Thanks in advance Emily.
In your functions.php: function my_body_class($classes) { if(is_page()){ global $page; $title = get_the_title( $page ); $classes[] = $title; } return $classes; } add_filter('body_class', 'my_body_class'); That will add the page title as a class to each page.
stackexchange-wordpress
{ "answer_score": 1, "question_score": 1, "tags": "php, pages, css" }
Using Static HTML instead of the `home_url()` WP function When I add links to pages in a custom WordPress theme I use the following function: `href="<?php echo esc_url(home_url( '/contact-page' ));?>"` If I don't use the `home_ur()` function, but the following code, it still works: `href="./contact-page"` I'm currently only doing this on a localhost (MAMP) set up. Is there any reason why I must use the `home_ur()` function instead of just the HTML code, which will be quicker to type, and obviously quicker for the server/browser to process? Emily.
href="./contact-page" * if you're on the homepage (`/`) this will become: `/contact-page` * if you're on another page named foo (`/foo/`) this will become `/foo/contact-page` This is due to `./` being a relative path. To avoid struggles like this, the method via `home_url()` is preferred because it creates absolute links/paths that will work from anywhere you call it. **Note:** You could use `href="/contact-page"` which is relative as well, but only to the domain and not the current page. However I can't tell you why WP rather uses and stores absolute URLs.
stackexchange-wordpress
{ "answer_score": 1, "question_score": 0, "tags": "functions, links, home url" }
[Zapier + WP Webhooks Pro]: Custom Fields get cut off at first comma or semicolon I'm using Zapier and WP Webhooks Pro to connect Google Sheet and WP to auto-publish posts for each row added to the spreadsheet. It works like as expected and all fields, including custom fields, are populated correctly expect those that have a string with a comma and/or semicolon. Those get cut off. **Setting up the custom field in Zapier** ![Setting up the custom field in Zapier]( **Success output in Zapier after posting to WP** ![Success output in Zapier after posting to WP]( **Custom field in WP (cut off after semicolon)** ![Custom field in WP]( Any help/direction on how to fix this issue would so much appreciated.
WP Webhooks Pro also accepts JSON constructs for more complex strings. Here's an example of how your **meta_input** can look like: {"meta_key":"data:image/png;base64,iVBOR......."} Simply paste that within your Zap and change the **data:image/png;bse64,iVBOR.......** to your dynamic value. :)
stackexchange-wordpress
{ "answer_score": 1, "question_score": 0, "tags": "rest api, api" }
Add a class with body_class to a specific url with parameter i try to add a class to the body for a specific page/url, which has a parameter at the end. the url looks like this: < with my code, the class is also added to the url without parameter. i know why this is happening, but i dont have any other idea to get this to work. function leweb_add_body_class_um_edit_profile( $classes ) { global $wp; $current_url = home_url( add_query_arg( array(), $wp->request ) ) . '/?um_action=edit'; $profile_url = um_user_profile_url() . '?um_action=edit'; if ( $profile_url == $current_url ) { $classes[] = 'leweb-um-profile-edit'; } return $classes; } add_filter( 'body_class','leweb_add_body_class_um_edit_profile' );
You're overcomplicating it a bit. `?um_action=edit` is a query string, and its values are available in the `$_GET` superglobal. To check if it exists, and has a specific value, you just need to do this: function leweb_add_body_class_um_edit_profile( $classes ) { if ( isset( $_GET['um_action'] ) && 'edit' === $_GET['um_action'] ) { $classes[] = 'leweb-um-profile-edit'; } return $classes; } add_filter( 'body_class','leweb_add_body_class_um_edit_profile' );
stackexchange-wordpress
{ "answer_score": 1, "question_score": 0, "tags": "parameter, body class" }
Gutenburg InnerBlock single child I have a custom block called `Custom Card` that takes an `InnerBlock` as a child. The purpose of this is because I want to format the content within the `Custom Card` a very specific way. The `Custom Card` has three allowed blocks: * `core/quote` * `core/video` * `core/image` The problem I've run into, is that after a user selects a block they can continue to add more blocks to the same Card. I want to limit the card to allow them to select _one_ of the three options they have available. What is some ways I can go about doing this?
The only way to do this at the moment is by using the `renderAppender`prop on`InnerBlocks`. This prop is only available in the Gutenberg plugin until WordPress 5.3 is released. The theory would be to use state in each `CustomCard` to track if there has been a block added, then return false from the `renderAppender` function so the user cannot insert more items.
stackexchange-wordpress
{ "answer_score": 2, "question_score": 1, "tags": "block editor" }
How to implement my custom development multiple PHP page work into Wordpress? I have developed a custom PHP page with filters, add to cart module, music playlist everything. How can i implement it into WordPress? I am a newbie, any help thanks. My custom PHP work directory structure : location : public_html/my_work website URL : website.com/my_work Everything is working good, but my WordPress Header and Footer are missing. How to implement my custom development multiple PHP page work into WordPress?
You can integrate your PHP file into WordPress with various ways like you can create a plugins and activate plugins and then you get all your PHP file accessible to WP functions. It's bit dirty but in your case if you wish you add `require_once(rtrim($_SERVER['DOCUMENT_ROOT'], '/') . '/wp-load.php');` on top of the files or if all files are loaded through index.php add the code on top of the file and after that you can include `get_header()` and in footer you can write `get_footer()`. In response to your question in chat for not accessing this in local host is, localhost $_SERVER['DOCUMENT_ROOT'] returns path to localhost/ and your package is accessible on localhost using < You have to modify for localhost or if you test this on server with subdomain you have to modify code like `require_once(rtrim($_SERVER['DOCUMENT_ROOT'], '/') . '/yoursite/wp-load.php');`
stackexchange-wordpress
{ "answer_score": -1, "question_score": 0, "tags": "templates" }
Override Blog pages show at most with get_posts any idea how to override Blog pages show at most with get_posts? I tried with numberposts but it isn't working. $args1 = array( 'post_type' => 'wpcp-events' 'numberposts' => -1, ); $posts = get_posts($args1); while (have_posts()) : the_post(); get_template_part('template-parts/event'); endwhile; rewind_posts();
In your code example, you're mixing two things. With `get_posts()` you'll get an array of posts, which you can use in a custom loop. $args1 = array( 'post_type' => 'wpcp-events' 'numberposts' => -1, ); $events = get_posts($args1); if ( $events ) { foreach ( $events as $post ) { setup_postdata( $post ); // make Loop tags available, sets current iteration to global $post get_template_part('template-parts/event'); } wp_reset_postdata(); // reset global $post } The `while (have_posts()) : the_post();` part handles the main loop. If you want to change how it works, you can use `pre_get_posts()`. I think this should work, function change_posts_per_page($query) { if ( ! is_admin() && $query->is_main_query() && 'wpcp-events' === $query->query['post_type'] ) { $query->set( 'posts_per_page', 50 ); } } add_action( 'pre_get_posts', 'change_posts_per_page' );
stackexchange-wordpress
{ "answer_score": 1, "question_score": 0, "tags": "get posts" }
How Do I Enqueue a Script into 2 different Footers on the Same Site? I have two different footers being used on a WordPress site. One is the standard `footer.php`the other is for the contact and legal pages and is `footer-contact.php` Calling them on the relevant page is straightforward enough - I just a use `<?php get_footer('contact'); ?>` on the pages where the contact footer is needed. This 2nd footer design though isn't calling in the scripts. In my functions.php file I use the following, with the last parameter being 'true' which places the JS in the footer. `wp_enqueue_script('main_js', get_theme_file_uri('/js/main.js'), NULL, '1.0', true);` How do I also enqueue my scripts into the second footer i.e. `footer-contact.php`
While `get_footer('name_template_file');` includes the defined footer template it does not output Wordpress _wp_enqueued_ styles and scripts that are defined to be output in the footer automatically. To let your page output all javascript files and stylesheets that supposed to go to the footer call `<?php wp_footer(); ?>` at the place you want them to be rendered. You could consider to place them in you main template (directly before `</body>` so there is no need to put them in every single footer template you might include. In most cases it should work fine.
stackexchange-wordpress
{ "answer_score": 1, "question_score": 0, "tags": "wp enqueue script, footer" }
Is there an equivalent of the PHP function sanitize_key in Gutenberg? In WordPress's PHP library there is a function `sanitize_key` used to generate database keys and HTML IDs. I'd like to generate a slug from a title that can be used as an HTML ID, from within a Gutenberg block. Is there an equivalent (or close to equivalent) function in the Gutenberg library, or must I make my own?
Use `import { cleanForSlug } from "@wordpress/editor";` in your block.js file to import the function in and then use the it like `cleanForSlug(stringToClean)` to create the ID's.
stackexchange-wordpress
{ "answer_score": 1, "question_score": 4, "tags": "javascript, slug, block editor, id, sanitization" }
WooCommerce - Reset quantity input field when variation changes Is there a way or a plugin to reset quantity input field every time a user changes the variation? I searched but i didn't find something similar or any hook. I tried the following jQuery event but it doesn't seem to fire function variation_select_change() { global $woocommerce; ?> <script> jQuery(function($){ $( ".variations_form" ).on( "woocommerce_variation_select_change", function () { alert( "Options changed" ); } ) }); </script>
To reset quantity input field to 1 when variation changes on product detail page use below code. you can set default quantity from `jQuery("[name='quantity']").val(1);`. i have tested and it is working fine for me. add_action( 'wp_footer', 'variation_change_update_qty' ); function variation_change_update_qty() { if (is_product()) { ?> <script> jQuery(function($){ $( ".variations_form" ).on( "woocommerce_variation_select_change", function () { jQuery("[name='quantity']").val(1); } ) }); </script> <?php } } let me know is this works for you!
stackexchange-wordpress
{ "answer_score": 1, "question_score": 1, "tags": "php, functions, woocommerce offtopic, jquery" }
Woocommerce login not working on the first try Sometimes the woocommerce login form is not working on the first try, but it is working on the second one. There are no error messages, the POST contains all the necesarry information, and I made sure that the submitted information is correct, yet the page gets reloaded without logging in the user (no error in the logs). On the second try, it works perfectly. I have tried debugging it, by following the user login process, that can be found here. Unfortunately I am having a very hard time with this simple issue. I have inserted a die(), in the wp_authenticate action, but on the first try, it seems that this action isn't even called. What should I check to find the problem?
I have solved the issue. If you are having a strange validation problem that ONLY happens when you first load a page, and you have Woocommerce running on this particular site it might help you too. Solution to my specific problem: /** * WooCommerce login not working on first try fix */ add_filter('nonce_user_logged_out', function($uid, $action) { if ($uid && $uid != 0 && $action && $action == 'woocommerce-login') { $uid = 0; } return $uid; }, 100, 2); More info about this issue here and here.
stackexchange-wordpress
{ "answer_score": 1, "question_score": 1, "tags": "woocommerce offtopic, login, wp login form" }
Wordpress HTTP API NTLM Authentication I was wondering if anyone has had to use NTLM authentication when using `wp_remote_get`? Trying to authenticate using Basic but that is returning the proxy error. When I use other authenticators for different APIs that do use the Basic method, it works flawlessly! Anyone got a solution for these?
In case anyone has issues like I did, I found this discussion where I added the code and instantly was authenticated. Not sure if its a Wordpress issue or a PHP one, but I feel that the `ANY` portion of the Wordpress authentication was getting blocked first to find the Proxy type, but timing out. Adding the code from this link worked: < add_action( 'http_api_curl', function( $handle ) { curl_setopt( $handle, CURLOPT_PROXYAUTH, CURLAUTH_BASIC ); });
stackexchange-wordpress
{ "answer_score": 1, "question_score": 0, "tags": "rest api, api, authentication, wp remote get" }
I have a 404 error on all my pages! What do I do? I have changed default permalinks into custom structure, and I got 404 error across all of my site.
Try to reset your permalink structure. In your WordPress Dashboard go to Settings > Permalinks. All custom post types require additional slugs like /portfolio-item/, /destination-item/, /tour-item/, /property-item/, /listing/ etc. So you probably made a typo in your custom structure. Select an alternative permalinks structure -> Save Changes. Change it back to your standard structure and hit Save Changes once again. If you’re still getting a “404 Page Not Found” error, try other remaining methods. ![permalink slug](
stackexchange-wordpress
{ "answer_score": 0, "question_score": 0, "tags": "permalinks, 404 error" }
Shortcode called twice I'm working on my product information using a shortcode who automatically can generate a table with information. But it looks like the shortcode gets called twice. I'm not a great back-end developer but I'm trying to learn some basics so I can make some basic PHP functions. I would really appreciate some help. Thanks in advance. My code looks like this: function displayTable() { echo '<table>'; echo '<tbody>'; $fields = get_field_objects(); foreach($fields as $field) { echo '<td>'; echo '<td>'. $field['label'] .'</td>'; echo '<td>'. $field['value'] .'</td>'; echo '</tr>'; } echo '</tbody>'; echo '</table>'; } add_shortcode('popnagel-tabel', 'displayTable')
Shortcodes should _never_ `echo`; they should always `return` the text to be displayed. See the **User Contributed Notes** in the `add_shortcode()` docs. Your code should read more like this: function displayTable() { $string = ''; $string .= '<table>'; $string .= '<tbody>'; $fields = get_field_objects(); foreach($fields as $field) { $string .= '<td>'; $string .= '<td>'. $field['label'] .'</td>'; $string .= '<td>'. $field['value'] .'</td>'; $string .= '</tr>'; } $string .= '</tbody>'; $string .= '</table>'; return $string; } add_shortcode('popnagel-tabel', 'displayTable');
stackexchange-wordpress
{ "answer_score": 4, "question_score": 0, "tags": "shortcode" }
Avoid removing duplicate posts I have an arrays of **IDs** which may contain duplicate values. Array ( [0] => 24 [1] => 11 [2] => 60 [3] => 11 ) I'd like to loop through those IDs using **WP Query** and the `post__in` property. Array ( 'post__in' => $posts, 'post_type' => 'any, 'orderby' => 'post__in' ) Everything work as expected, but duplicate IDs are removed by default. Is there any way to prevent it?
It's a bit less efficient, but if you have an array of IDs, possibly including duplicates, and want to get the posts for each, I'd suggest use `get_post()` on each ID, giving you an array of posts. $post_ids = [ 24, 11, 60, 11 ]; $posts = array_map( 'get_post', $post_ids ); global $post; foreach ( $posts as $post ) : setup_postdata( $post ); // the_title(); etc. endforeach;
stackexchange-wordpress
{ "answer_score": 0, "question_score": 0, "tags": "wp query, loop" }
Prepare WPDB with meta key and meta value I'm trying to prepare WPDB by post type, meta key, and meta value global $post; global $wpdb; $rid = absint($_POST["rid"]); // number $last_id = absint($_POST["lastID"]); // post ID $query = $wpdb->prepare( " SELECT ID FROM $wpdb->posts WHERE ID > %d AND wp_posts.post_type = 'room' AND wp_postmeta.meta_key = 'rid' AND wp_postmeta.meta_value = %s ORDER BY wp_posts.ID DESC LIMIT 0, 1", $last_id, $rid); $results = $wpdb->get_results( $query ); foreach ( $results as $row ) { echo $row->ID; } die(); All I want to do is get the last ID that fits the criteria
If you run this query manually, you should get a response like > (1054, "Unknown column 'wp_postmeta.meta_key' in 'where clause'") Long story short, `wp_postmeta.meta_key` is not a valid column of `wp_posts`. You need to `JOIN` the postmeta table to be able to use its columns. (There are many resources out there that explain `JOIN`, one would be this answer.) $query = $wpdb->prepare( " SELECT p.ID FROM {$wpdb->posts} AS p INNER JOIN {$wpdb->postmeta} AS pm ON p.ID = pm.post_id AND pm.meta_key = %s WHERE p.ID > %d AND p.post_type = %s AND pm.meta_value = %s ORDER BY p.ID DESC LIMIT 0, 1 ", 'rid', $last_id, 'room', $rid );
stackexchange-wordpress
{ "answer_score": 0, "question_score": 0, "tags": "wpdb, meta value" }
Bootstrap doesn't work on admin menu page-How to override wp-admin style? I am building a plugin and i use bootstrap to style it but i notice some components styles don't work properly.Someone suggested in a blog post to use `wp_deregister_style('wp-admin');` which **did** fix my issues but broke the rest of the wp-admin page. Is there a way to override the css that loads in the wpbody-content?
It turned out that there was already a .card class from wp that had some extra attributes than bootstrap's so they were overriding it.
stackexchange-wordpress
{ "answer_score": 1, "question_score": 2, "tags": "plugin development, admin menu, twitter bootstrap" }
How to remove "Archives" after category name? There are many similar questions, but none of them have exactly the same issue as I do. Unfortunately the solutions suggested there have not fixed my issue. After selecting a category in my Shop page, the page title turns into "Categoryname Archives - Storename". I would like to remove the "Archives" part from the title, or atleast translate it. I have not found a way to translate or remove it. I am using Loco Translate for my translation needs. All links with examples: < \- Our Store page. < \- A category named "Kruusid" is selected, the title is incorrect. Is this a theme, SEO or some other problem? I have tried some suggestions to make changes in Yoast SEO, but for that I would need to change a certain page's SEO options. I do not know which page is handling the category selection (so < Any advice?
This should be Yoast SEO related. In your WordPress admin dashboard navigate to **SEO** -> **Search Appearance**. Then, on the **Taxonomies** tab you can edit the "Archives" text (and many other strings).
stackexchange-wordpress
{ "answer_score": -1, "question_score": 0, "tags": "archives" }
why is my postmeta table is so heavy One of my database is realy heavy (+100Mo) for a site with not so many content (like 40 pages & 10 posts)). I found in phpmyadmin that my table "postmeta" is 95Mo. So i wonder to know what are the data that takes so many place... ! i run a DB optimizer plugin (Advanced Database Cleaner) that help me go down to 92Mo, for only 2261 rows in table. ( Before, whas much more but i don't remember the number of lines ). usualy my WP postmeta table is 2 to 5 mo for 4k rows... I thinks this is linked to my theme, but i have no idea how to know wich data is so heavy. So how can i know wich are the heavy lines in my database ? in text export, the more biggest rows is like this : (maybe it can help ?) <
Many of the Page builder plugins records page/post specific data in the meta data of the Post/Page which is saved in wp_postmeta table. Similarly, you are using Elementor Pro plugin which is saving post configuration data there. IMO, You should not be worried about this data otherwise you can contact plugin author to optimize it.
stackexchange-wordpress
{ "answer_score": 1, "question_score": 0, "tags": "post meta, mysql" }
How to import the data to the post from an external URL? I want to show the special data (a number) inside a WordPress page. This data is generated by an external API and changes from time to time. I don't have any clue how to manage this. The data I need is returned when I send `GET` to the ` The data has to be shown inside the post.
Just use PHP code, for example : $price = floatval( file_get_contents( ' ) ); echo $price; `floatval` is here to sanitize and assure you to have a float number.
stackexchange-wordpress
{ "answer_score": 0, "question_score": 0, "tags": "wp remote get" }
How to design WooCommerce-like admin tabs for plugin settings page? I'm working on a WooCommerce addon/plugin and created a custom admin sub page under WooCommerce menu in dashboard. Now I am looking to add tabs and sub navigation as per the Settings page under WooCommerce. ![WooCommerce settings tab]( I am wondering if there is a WordPress/WooCommerce of doing it, or do I need to just replicate it using custom code? Edit: ideally it should be on my custom admin sub page, but guidance to add a new tab to WooCommerce->Settings is also appreciated.
I've figured it out how to do it on my custom admin page. You can use default wordpress classes and get variable trickery like so: <?php if( isset( $_GET[ 'tab' ] ) ) { $active_tab = $_GET[ 'tab' ]; } // end if ?> <h2 class="nav-tab-wrapper"> <a href="?page=sandbox_theme_options&tab=display_options" class="nav-tab <?php echo $active_tab == 'display_options' ? 'nav-tab-active' : ''; ?>">Display Options</a> <a href="?page=sandbox_theme_options&tab=social_options" class="nav-tab <?php echo $active_tab == 'social_options' ? 'nav-tab-active' : ''; ?>">Social Options</a> </h2> And then wrap everything else in `if($active_tab == 'desired_option'){}` statements. Credit: <
stackexchange-wordpress
{ "answer_score": 0, "question_score": -1, "tags": "plugin development, woocommerce offtopic, admin menu" }
bloginfo url in javascript I'm trying to set `<?php bloginfo('template_url'); ?>` in a variable on Javascript, and then to set `src` of an `img` element, but in the html it's been printed as `src="<?php bloginfo('template_url'); ?>"` and not as the actually `url`. This is how I tried to do it: `var wpTemplateUrl = "<?php bloginfo('template_url'); ?>"; primaryImg.src = wpTemplateUrl;`
Try using some API from WordPress itself - <
stackexchange-wordpress
{ "answer_score": 0, "question_score": 0, "tags": "php, images, javascript, urls" }
How can I get blog content from SFTP? I inherited a site that was compromised (I'm not sure what version of wordpress, the crash happened last summer). I have CLI access, and can SFTP into the server. The only thing I want to get is the content of the blogs. I was able to see the mysql files from SFTP, but they are just the .frm files. What is the best way to get this content?
What I ended up doing since I had Mysql/SFTP access, was: 1. create a dump using these instructions: here 2. get the .sql file using cyberduck(newest version of mac conflicts with filezilla) 3. open a local mysql workbench 4. Run the .sql file 5. using a select, get the blog info I needed
stackexchange-wordpress
{ "answer_score": 0, "question_score": 0, "tags": "blog, filesystem, bloginfo, account" }
How to remove X-Frame-Options: SAMEORIGIN" from WordPress? I want to temporarily remove `X-Frame-Options: SAMEORIGIN` and need to allow all domains. I have already tried the following ways. 1. Removing `send_frame_options_header` from `./wp-includes/default-filters.php` 2. `remove_action('login_init', 'send_frame_options_header');` 3. Removing `@header( ‘X-Frame-Options: SAMEORIGIN’ );` from `/wp-includes/functions.php` None of the above doesn't work. PS: I don't use any security plugin either.
Check this question How does wordpress restrict X-FRAME to sameorigin?. The questioner's issue was resolved by modifying his site's .htaccess file by adding the below line to it as his Web Host set the X-Frame-Option. Header always unset X-Frame-Options You can check if that works for you.
stackexchange-wordpress
{ "answer_score": 5, "question_score": 3, "tags": "filters, headers, core, core modifications" }
Filter get_page_by_path() Is there a way to filter `get_page_by_path()`? I am trying to allow duplicate slugs for pages, so that two pages can have the same slug if they have different meta value for a specific meta key. Thanks for the help in advance!
Theres no filter for that function. You can find the code in wp_includes/post.php (Obviously don't edit it there). Core File
stackexchange-wordpress
{ "answer_score": 1, "question_score": 0, "tags": "filters, actions" }
How to remove the bottom table headers (column names) in WP_List_Table? By default, the `WP_List_Table` has column names at the top and the bottom of the table. How can I remove the bottom table headers? Thanks. p.s. I have already subclassed the `WP_List_Table`.
You can override the `WP_List_Table::display()` method and remove the `tfoot` which contains the bottom table headers: <tfoot> <tr> <?php $this->print_column_headers( false ); ?> </tr> </tfoot> Or you can add a specific `class` to the relevant admin page and use CSS to _visually_ hide the bottom table headers: .my-plugin-foo-page table.wp-list-table > tfoot { display: none; }
stackexchange-wordpress
{ "answer_score": 1, "question_score": 0, "tags": "wp list table" }
How to avoid images appear as post in google search? I'm helping my friend with his WordPress website and recently we noticed that in google search, some images appear as page/post. Also when clicked they seem to be reached in a page. I don't know what causes this. Need help immediately. Thanks in advance. ![appearance in google search]( ![Reachable as page](
This is because your attachment pages are being indexed by Google. A simple fix would be to install the WordPress SEO plugin and use it to redirect the attachment page URLs to the original media (your images). After you install the plugin, go to "Search Appearance", then click the "Media" tab, and toggle the "Redirect attachment URLs to the attachment itself?" to "yes". You can read the full details in this Yoast Article or in this Knowledge Base Article.
stackexchange-wordpress
{ "answer_score": 0, "question_score": 0, "tags": "images, seo, google" }
WP_Query with Metavalue I have developed this function but returns 0 results. I think there is a problem with the way I am passing the meta_value arguments. Any help? add_shortcode( 'sc_count_brands', 'sc_count_brands_code' ); function sc_count_brands_code($atts) { $values = shortcode_atts( array('category' => 'Horology',), $atts ); $query = new WP_Query( array( 'post_type' => 'brands', 'post_status' => 'publish', 'meta_key' => 'br_category', 'meta_value' => esc_attr($values['category']) ) ); $countn = $query->found_posts; $buffer = '<span class="magby">Featuring </span><span class="axiac">' . $countn . '</span><span class="magby"> brands</span>'; wp_reset_postdata(); return $buffer; }
I would recommand to add meta_query in array param, try this add_shortcode( 'sc_count_brands', 'sc_count_brands_code' ); function sc_count_brands_code($atts) { $values = shortcode_atts( array('category' => 'Horology',), $atts ); $args = array( 'post_type' => 'brands', 'post_status' => 'publish', 'meta_query' => array( array( 'key' => 'br_category', 'value' => esc_attr($values['category']), 'compare' => '=' ), ), ); $query = new WP_Query( $args ); $countn = $query->found_posts; $buffer = '<span class="magby">Featuring </span><span class="axiac">' . $countn . '</span><span class="magby"> brands</span>'; wp_reset_postdata(); return $buffer; }
stackexchange-wordpress
{ "answer_score": 2, "question_score": 1, "tags": "wp query" }
Gutenberg: useDispatch is not a function - @wordpress/data included I have the `@wordpress/data` package installed, but I can't use `useDispatch` in my block edit function: const { registerBlockType } = wp.blocks; const { useDispatch, useSelect } = wp.data; . . . registerBlockType( 'rb-bootstrap/grid', { ... edit: function( props ) { const { replaceInnerBlocks } = useDispatch("core/block-editor"); } } > TypeError: useDispatch is not a function What am I missing?
I used to have the same problem. After I updated Wordpress, window.wp.data.useDispatch was available. I'm guessing you also have an out of date Wordpress / Gutenberg
stackexchange-wordpress
{ "answer_score": 0, "question_score": 2, "tags": "plugin development, javascript, block editor" }
Comments change the template name I am following this tutorial: < How come when I type the following block of code in a file named page-archives.php, the template name changes? For example, if I typed in "Archive2" the dropdown list would display Archive2. **I thought comments didn't have any effect.** <?php /* Template Name: Archives */ ?>
That comment is what makes a file as a (custom) page template. Relevant excerpt from Creating Custom Page Templates for Global Use: > To create a global template, write an opening PHP comment at the top of the file that states the template’s name. > > > <?php /* Template Name: Example Template */ ?> > And the tutorial actually says, "the name of the template that appears in the Page Attributes section of the WordPress page editor is defined using the _Template Name_ string". So, whatever name you define there would be the name used in the templates dropdown. E.g. `Template Name: Archive2` would assign the template name to `Archive2`.
stackexchange-wordpress
{ "answer_score": 1, "question_score": 0, "tags": "comments" }
Wordpress "wpdb->update" - Append Text Value I am trying to update a table column by appending some text to the existing value in the column. Basically, I am trying to do something like this: $wpdb->update('table_name', array('notes' => notes + 'some text here to append')) ,array('note_id' => 313) ); Is this possible?
Short answer: it's not possible. Long answer: you should try `$wpdb->query` instead and write a regular SQL query, something like this: `UPDATE table_name SET notes = CONCAT(notes, 'text to append') WHERE note_id = '313'` Please note it's only an example and you should use `$wpdb->prepare` to also sanitize variables properly.
stackexchange-wordpress
{ "answer_score": 1, "question_score": 0, "tags": "wpdb" }
How to Insert an advert banner for every third Slide using JS Composer Slider Hi I am working on my website and I want to ADD an ADVERT BANNER for every THIRD Post-Slider. I have previously used this code in a loop but it doesn't work the same for a SLIDER - Here is the Code I used previously on another website: if (in_category(37)) { $post_counter++; if ($post_counter == 1 || $post_counter == 3) { ?> Let me know if you have any ideas...
Thanks! Yes I edited the APP.min.JS file in order to show custom adverts on the Jcomposer Page builder...
stackexchange-wordpress
{ "answer_score": 0, "question_score": 0, "tags": "php" }
rest Api jwt authentication for get methodes I'm developing an API for my Wordpress website, I want to authorize all API request using jwt token. already installed and configured this plugin "JWT Authentication for WP REST API".But when I try via get/post methode my API will return data with out passing jwt access token how can I prevent this? function api_version() { $api=array( "version"=> "v1", "time"=>date('Y-m-d H:i:s P')); return $api; } add_action( 'rest_api_init', function () { register_rest_route( 'v1/', 'info', array( 'methods' => 'GET', 'callback' => 'api_version', ) ); } );
The token just authenticates the request as coming from a specific user. You still need to use the permissions callback to check if that user has permission for whatever it is you're doing. If you omit the `permissions_callback` argument when registering the route then the route is public. If you only need to check if there _is_ a user, and not specific permissions, you could just use `is_user_logged_in()`: register_rest_route( 'v1/', 'info', array( 'methods' => 'GET', 'callback' => 'api_version', 'permissions_callback' => function() { return is_user_logged_in(); }, ) );
stackexchange-wordpress
{ "answer_score": 1, "question_score": 0, "tags": "rest api" }
Undefined variable error in new function I wanted make function to count the time last the user read the article but after putting it in `fuctions.php` I see this error: **Notice: Undefined variable: post in /home/karnetac/public_html/wp-content/themes/karneta/functions.php on line 2 Notice: Trying to get property 'ID' of non-object in /home/karnetac/public_html/wp-content/themes/karneta/functions.php on line 2** my codes: function sh_reading_time() { $content = get_post_field( 'post_content', $post->ID ); $word_count = str_word_count( strip_tags( $content ) ); $readingtime = ceil($word_count / 200); return $readingtime; } would you plese help me? I think it is easy but I can not fix it now. thanks
I believe that's telling you that `$post` (in `$post->ID`) is undefined. Try this instead: function sh_reading_time() { $content = get_post_field( 'post_content', get_the_ID() ); $word_count = str_word_count( strip_tags( $content ) ); $readingtime = ceil($word_count / 200); if ($readingtime == 1) { $timer = " minute"; } else { $timer = " minutes"; } $totalreadingtime = $readingtime . $timer; return $totalreadingtime ; }
stackexchange-wordpress
{ "answer_score": 1, "question_score": 0, "tags": "functions, the content, variables" }
Difference between deactivating, uninstalling, and deleting plugins I understand the difference between deactivation and uninstallation. But the CLI also has a delete option. How does it differ? To be safe, should I deactivate, then uninstall, then delete?
From the docs about `wp plugin delete`: > Deletes plugin files without deactivating or uninstalling. so after runing the comand on a plugin I would expect the admin plugin page showing the warning about the missing plugin being deactivated and all the uninstalling database related actions have not taken place. Just run uninstall with the `--deactivate` option and you are done. < <
stackexchange-wordpress
{ "answer_score": 5, "question_score": 4, "tags": "plugins, wp cli" }
What hook should I use to add post meta data with on update? I'm looking to use the bitly api to generate a shortened url for all posts and pages. My plan is to generate this when the post is saved, then save the shortened to the post when the API call is answered. But I'm worried that if I use the wrong hook I'll end up in an infinite loop of listening for the update hook, then triggering the update hook. So how can I avoid this, or is there a hook I can use that will trigger when a post is updated but wouldn't trigger when I add meta data to a post
Use the hook 'save_post' that pass 1 arguments: $post_id. Update_post_meta won't trigger save_post. add_action('save_post', 'custom_add_meta', 10, 1); function custom_add_meta($post_id){ update_post_meta($post_id, 'meta_key', $value); }
stackexchange-wordpress
{ "answer_score": 0, "question_score": 0, "tags": "hooks" }
get_template_directory_uri() generates wrong path I've uploaded a wordpress site but it's missing javascript and css. The links on the head still have the local path (`src=' and not the new ones. So I guess it has to do with get_template_direcory_uri() that I use in fucntions.php to apply my javascript/jquery,bootstrap,css etc. How yo fix that? I've tried adding to config.php: define( 'WP_SITEURL', ' . $_SERVER['HTTP_HOST'] ); define( 'WP_HOME', ' . $_SERVER['HTTP_HOST'] ); and define( 'WP_HOME', ' ); define( 'WP_SITEURL', ' ); but they didn't help...
Do your URL change up in phpMyAdmin with SQL language: # Change website url UPDATE wp_options SET option_value = replace(option_value, ' WHERE option_name = 'home' OR option_name = 'siteurl'; # Change GUID URL UPDATE wp_posts SET guid = REPLACE (guid, ' # Change url of medias, post, page, etc. UPDATE wp_posts SET post_content = REPLACE (post_content, ' # Change meta data url UPDATE wp_postmeta SET meta_value = REPLACE (meta_value, '
stackexchange-wordpress
{ "answer_score": 1, "question_score": 0, "tags": "css, javascript, uploads" }
Unable to login to a https website via the app after changing from http Put simply, I am unable to login to my site through the wordpress app. I was able to previously login, but since the update I have not been able to. I believe this may have happened since I moved the site to `https` from `http` There is nothing in access/error logs just this entry with each login: `[28/Oct/2019:15:17:02 +0000] "POST /xmlrpc.php HTTP/1.1" 200 4131` ![I set url to <code>https</code>]( ![enter image description here]( "I set url to `https` ") The error received when logging in is: `The username and password you entered is incorrect.` However logging in via the `desktop/chrome mobile` everything works without a problem. So I know it is not a `php/server` error. ![enter image description here](
Maybe it has to do with the reCaptcha Protection on your Login Page? This is not built into Wordpress, but has to be installed by plugin. If the plugin changes the login-procedure, then maybe the login by app is changed too. Also, a "recaptcha on Login Page" is often times realized by security plugins, which also recently started to incorporate an option to disable logging in per XML-RPC, which is the Login Method used by the Wordpress App. Try to disable the Plugin which puts the recaptcha on the login page and try logging in again. If you can log in again, you know to search in the options of this plugin.
stackexchange-wordpress
{ "answer_score": 0, "question_score": 0, "tags": "database, login, mobile" }
in post content shortcode works, but hardcoded in same page template doesn't? So I have a super simple Woocommerce shortcode [product_categories], It's supposed to show product categories from the shop. It does this job perfectly if I put it inside the contents of a page as such: [product_categories]. However, if I put the same thing into the template directly it suddenly returns the first post of current category? What?! So in my template I have only these two rows: <?php echo do_shortcode('[product categories]'); // this returns a single product which is wrong and totally weird ?> <?php the_content(); // this returns the categories as intended ?> I never knew these two methods have some kind of difference. How can I make the shortcode work with the echo way?
I was lacking the underscore in [product categories]. <?php echo do_shortcode('[product_categories]'); ?> Above code with "_" returns the correct answer.
stackexchange-wordpress
{ "answer_score": 0, "question_score": 0, "tags": "categories, woocommerce offtopic, shortcode" }
where to add this filter? in which file should be added? For wordpress language switcher, this post was helpful for others, but I don't know where to add the mentioned filter How to change language file used by _e function add_filter('locale', function($locale) { return esc_attr($_GET['language']); });
Add this code to your functions.php file in your WordPress theme files. See this article for some additional help: <
stackexchange-wordpress
{ "answer_score": 0, "question_score": 0, "tags": "multi language, language" }
Hide Users by user role in Worpress I'm trying to only show authors in my user's page. I was hoping that user role editor could do the trick but apparently not. Is there a way to do it? Thanks
you could use wp_list_authors for list your authors in your user page. Put a look here: < Does it help you? EDIT: According to our communications: $users_array = array(); $users = get_users('role=author'); if(count($users) > 0){ foreach($users as $user){ $users_array[] = $user->ID; } } add $users_array instead of array(1, 3, 5) ...
stackexchange-wordpress
{ "answer_score": 1, "question_score": 0, "tags": "user roles" }
Edit post locked notification dialog on edit post screen (post.php)... hook maybe? Creating a management application for my company and other utility companies... would be nice to remove the Preview button via php without a core hack... I have to hack the core just a little anyhow and am keeping detailed records but if it is possible not to do this that would be very good. Any feedback much appreciated
I believe the easiest approach is to hide that Preview button via CSS. Here is a snippet or you can add that style to a pre-existing wp-admin stylesheet that you might have already included. add_action( 'admin_head-post.php', function(){ echo '<style>'; echo '.edit-post-header__settings .editor-post-preview { display: none !important; }'; echo '</style>'; }); I tried digging through the core and I don't see any way to filter those links out. Hope that helps!!
stackexchange-wordpress
{ "answer_score": 1, "question_score": 0, "tags": "posts" }
Infinite redirects after changing the permalink of a page I changed the permalink of a page in the WordPress site. It caused to infinitely redirect between the new and old permalink. To test the scenario I changed the permalink several times and now it has began to redirect all among those URLs. What may be the issue?
I had the same problem after changing the URL of a page. I found that issue occurred due to a plugin "Yoast SEO". That plugin keeps old URLs and new URLs.If a page redirects unexpectedly or causes a redirect loop only when your plugin is active, this means a redirect has been added to your plugin. To solve this go to the redirects section under SEO plugin and delete the relevant redirect record. For more details, you can refer here. <
stackexchange-wordpress
{ "answer_score": 1, "question_score": 1, "tags": "permalinks, redirect" }
Site too Slow to establish db connection? After deployment site was too slow on analysis it takes time at db connection side. DB is in remote server. Trying queries without WordPress gives faster response. But WordPress takes around 40 sec waiting for DB ?
This has something to do with your database server to speed up response time. Also may be it is validating your IP from where your are pinging . If you can whitelist your IP,the connection would be more reliable and may increase ping time.
stackexchange-wordpress
{ "answer_score": 1, "question_score": -1, "tags": "performance" }
Change position of header image with default 2019 theme I am currently setting up a Wordpress website based on the default Twenty Nineteen theme. The theme allows to use a header image. The default position is on the top left as can be seen in the following image (red square). ![enter image description here]( However, I would like to change the position of the header image. I would like to display the header image at the top right, next to the navigation links as can be seen in the following picture (see position of the red square). ![enter image description here]( Obviously, the newly positioned header image would have a different size, that is, it would be wider. My question is: Is there any best practice procedure to change the position of the header image for the Twenty Nineteen theme? I know that the theme is heavily tailored toward mobile display and therefore the structure of the page may not allow such a modification, but maybe there is away.
In the header file for the child theme there is a div with class of "site-branding-container" It contains an h1 element and a p element. Just ad an img element after the p element. i.e. <div class="site-branding-container"> <div class="site-branding"> <h1 class="site-title"><a href=" rel="home">Theme Preview</a></h1> <p class="site-description">Previewing Another WordPress Blog</p> <img src=" </div><!-- .site-branding --> </div> Then adjust with css.
stackexchange-wordpress
{ "answer_score": 1, "question_score": 0, "tags": "custom header, header image" }
How do I find the page/url where a search came from when using pre_get_posts filter? When I use pre_get_posts filter, I want to check what url/page the search query came from, but the $query var does not appear to contain that information. How do I retreive it in my function below? function my_custom_search_results($query) { if ( is_search() && $query->is_main_query() ) { // How do I check the page/url of this search for where it came from? } return $query; } add_filter( 'pre_get_posts','my_custom_search_results' );
You can simply use `$_SERVER['HTTP_REFERER']` If you prefer WordPress way, you can use `wp_get_referer()` function.
stackexchange-wordpress
{ "answer_score": 1, "question_score": 0, "tags": "plugin development" }
Woocommerce change the price of products in the database I'm trying to adjust the price of products in the database. I need to customize products that have custom taxonomy manufactory with id 270. I can change a simple product with this code: UPDATE wp_postmeta LEFT JOIN wp_term_relationships ON wp_term_relationships.object_id = wp_postmeta.post_id SET wp_postmeta.meta_value = wp_postmeta.meta_value*1.05 WHERE wp_postmeta.meta_key = "_regular_price" AND wp_term_relationships.term_taxonomy_id = "270" But it won't change prices for variable products ... Can anyone help me?
So after a few attempts, I managed to change the price for variable products. If someone needs to send my code: UPDATE wp_postmeta LEFT JOIN wp_posts ON wp_posts.id = wp_postmeta.post_id LEFT JOIN wp_term_relationships ON wp_posts.post_parent = wp_term_relationships.object_id SET wp_postmeta.meta_value = wp_postmeta.meta_value*1.05 WHERE wp_posts.post_type = 'product_variation' AND wp_postmeta.meta_key = '_regular_price' AND wp_term_relationships.term_taxonomy_id = '2396'
stackexchange-wordpress
{ "answer_score": 0, "question_score": 0, "tags": "woocommerce offtopic, sql" }
cURL needing to loop through all "next_page" When using cURL, how would I be able to include a call inside my get_all that basically will loop through all the next_pages, get the data and then outpul it to $response->data when the "next_page" parameter becomes null? **Here is the method** : public function get_all() { return $response->data; } **This is what $response->data is returning as of now** (The cURL code wasn't included here): "paginator": { "total": 3092, "per_page": 500, "current_page": 2, "last_page": 7, "prev_page": " "next_page": " }, "data": [ { "id": 1592, etc....
You could try something like: $url = ' $data = array(); while ( $url ) { $response = $this->request( $url ); $data = array_merge( $data, $response->data ); // if this is not the last page, get the next page URL if ( $response->paginator->current_page != $response->paginator->last_page ) { $url = $response->paginator->next_page; } else {$url = false;} } return $data;
stackexchange-wordpress
{ "answer_score": 0, "question_score": 0, "tags": "php, functions, loop" }
When is it useful to use wp_verify_nonce I know that `wp_verify_nonce()` is used to make sure that the `$_POST` is coming from a safe place. I am developing a WordPress plugin which creates custom lists. In order to do that the web site owner has to access to the plugin settings login in your `wp-admin` server. Is necessary to use `wp_create_nonce()` & `wp_verify_nonce()` if the form can only been accessed after wp-admin login?
Yes, nonces should always be used when an authenticated user is triggering an action via a GET/POST request. One of the main purposes of the nonce is it ensure that the current user actually intended to trigger this request. It prevents the security vulnerability known as Cross-Site Request Forgery (CSRF), where an attacker can trick an authenticated user into taking an action they didn't intend to. Checking for a valid nonce prevents this, because the attacker cannot guess the nonce, so they can't forge a form submission request and trick an admin into submitting it. Note that the the attacker doesn't have to have access to the form itself, as your plugin presents it, in order to perform this attack. They can create their own imitation form or trigger the request in another way.
stackexchange-wordpress
{ "answer_score": 2, "question_score": 2, "tags": "plugins, forms, security, nonce" }
How to retrieve all meta data directly from the $post object? Such as $post->related_topics? I set up a meta field `related_topics` that I use to associate `lesson` `topics` to a custom post type `lesson`. I read here < that you can access meta fields directly from a post object in the manner `$post->my_field`. For a given `lesson` there could be several related `topics`. For a given `lesson` that has multiple `topics`, I noticed that `$post->related_topics` only returns the first `topic` instance, when in fact there are more than one. Is there some method to use, something like `$post->related_topics->all()`? Maybe with this convention only one item is returned by default even if there is a collection? thanks, Brian
By calling $post->related_topics you are using the magic functions of the object ( __get and __isset ) To make it simple, behind the scenes it is the same as : get_post_meta( $post->ID, 'related_topics', true ); So you are just abstracting the use of the function get_post_meta. And as you can see, the third argument is defined as TRUE. And this tells the function to return a single value. So its ok if your meta is a single value, but if you have multiple values, then you must set the third argument as false. Thus you shouldn't use the magic functions, but rather call get_post_meta yourself. So, just use : $topics = get_post_meta( $post->ID, 'related_topics', false); like that you have an array of values
stackexchange-wordpress
{ "answer_score": 0, "question_score": 0, "tags": "posts, post meta" }
How to check False booleans when using get_option? Whenenver you do `get_option( 'my_option' )` and that `my_option` is literally `False` itself, you cannot simply check for `if( !get_option( 'my_option' ) )`, to see if the value exists, because it'll return `False` and the check will be meaningless. Is there no way to check whether or not the option key `my_option` exists?
You can set a default value for when the option does not exist. This way you can check to see if the returned value is false, or if it doesn't exist at all: $value = get_option( 'my_option', $default_value ); if( $value == $default_value ) { // Option does not exist } elseif ( $value == false ) { // Option's value is equal to false }
stackexchange-wordpress
{ "answer_score": 3, "question_score": 0, "tags": "options" }
Allow a page to be edited by a specific custom role I have created multiple custom roles using the members plugin by Justin Tadlock. Now i want certain pages to only be editable by the custom roles i select for them. Is there a plugin i can use for that functionality or is that something i would have to code myself? Thanks in advance.
I fixed it already. I used the ACF User role selector to select roles per page. Then i made a checker for every page that matches the current logged in role with the role selected on the page.
stackexchange-wordpress
{ "answer_score": 0, "question_score": 0, "tags": "plugins, pages, user roles, members" }
How to find the list of custom post type where logged in user is author I need to find a list of custom posts where the logged in user is the author of the post
I have found a solution for it and here is it $current_user = wp_get_current_user(); $userID = $current_user->ID; $args =array( 'author' => $userID,'post_type' => 'custom_post' ) ; $authors_posts = get_posts($args); foreach ( $authors_posts as $authors_post ) { $content= $authors_post->post_title; } echo $content;
stackexchange-wordpress
{ "answer_score": 1, "question_score": 0, "tags": "plugins, themes" }
Do shortcodes affect page indexing by search engines? I am using this(Insert PHP Code Snippet) plugin for inserting PHP code in a HTML page. My Question is by using these shortcodes are there any bad effects when it comes to **SEO** and **page indexing** by search engines. Why I have this doubt is because I am using another plugin to count the words on each page. The page which uses shortcode showing fewer words even it has more words. So I just wanted an answer for this one. Thanks
No. Search engines can only browse and index the final output of the page, which includes the shortcode output. Your word count plugin is only counting the words entered into the post editor. Those two things work completely differently.
stackexchange-wordpress
{ "answer_score": 1, "question_score": -1, "tags": "plugins, shortcode, seo" }
How do I fix Undefined variable using $_POST in function? I have the following `function` but with this error: `Notice: Undefined variable: rating`. hoa can I fix it? function save_comment_meta_rating($comment_id){ if(!empty($_POST['rating'])) $rating = sanitize_text_field($_POST['rating']); add_comment_meta($comment_id,'rating',$rating); // Then update the average rating. update_post_avg_rating( $comment_id ); } add_action('comment_post','save_comment_meta_rating'); Thanks
Your check is incorrect: right now, it tries to access `$_POST['rating']`, which might not be set, and then checks whether that value is empty. Furthermore, you should scope your `if` statement with brackets, because right now, your code will try and update the average rating even if no new rating is provided. Try: function save_comment_meta_rating( $comment_id ){ if ( ! array_key_exists( 'rating', $_POST ) || empty( $_POST['rating'] ) ) { return; } $rating = sanitize_text_field( $_POST['rating'] ); add_comment_meta( $comment_id, 'rating', $rating ); // Then update the average rating. update_post_avg_rating( $comment_id ); } add_action( 'comment_post', 'save_comment_meta_rating' );
stackexchange-wordpress
{ "answer_score": 0, "question_score": 0, "tags": "php, functions, variables" }
Make categories appear random I have 5 big categories and there are many small categories in them. If I click on the category menu, I can see the posts in order of date. But I want it to be displayed randomly. How can I make a post appear randomly?
You could hook into the `pre_get_posts` action hook and set the posts' order to random only for specific categories. Here's a basic example on how to achieve so: function sort_posts_randomly( $query ) { if ( ! is_admin() && $query->is_main_query() ) { if ( is_category( 'category id, slug, or name' ) ) { // Sort the posts randomly $query->set( 'orderby', 'rand' ); } } } add_action( 'pre_get_posts', 'sort_posts_randomly' );
stackexchange-wordpress
{ "answer_score": 0, "question_score": 0, "tags": "posts, categories" }
Jupiter theme Mega menu option not available I am using WordPress > Jupiter theme version 1.0 Wordpress version is > 4.7.15 Mega menu option was enabled for some menu items and it was working perfectly for years. But suddenly from several weeks ago, mega menu was disappeared. Even the checkbox to enable that feature also not available. As a quick fix, I restored a several weeks old backup. The restored site had the mega menu, but after several hours it was gone again. What may be the reason for this behaviour? How can I get mega menu back?
I had the same issue and finally, I found the reason and the solution myself. The issue occurred due to a conflict of plugins. The latest popup maker plugin makes the mega menu checkbox invisible. To get back the checkbox in the menu, follow these steps. Popup Maker > Settings > Misc : **Disable Popups Menu Editor** (Use this if there is a conflict with your theme or another plugin in the nav menu editor.)
stackexchange-wordpress
{ "answer_score": 0, "question_score": 1, "tags": "menus" }
Block Editor: How to get title and post content within the WordPress admin UI in Javascript? Adapting some old SEO module (which was written for TinyMCE), I have to access the current post title and post content via JavaScript. I have been avoiding Gutenberg in the past, but it seems like this will be no longer possible. Within the old SEO module there are the following lines in the `admin.js`: var title = $('#title').val().trim(); var content = $('#content').val().trim(); Those fields do not exist in Gutenberg anymore. I have tried to find the correct way to do this in the docs, but no luck so far. I have found: wp.data.select("core/editor").getBlocks() wp.data.select("core") But both seem to be empty arrays in my case (although this post has content). I basically just need a way to get the textual contents of all blocks (and maybe separately from the main post title if this is possible). Who knows how to do that?
If we do this in the browser dev tools console: var b = wp.data.select("core/editor"); We can then inspect the `b` variable to see what functions it exposes via autocomplete, or debugging tools. Notice, I didn't call `getBlocks()`, the post title has never been a part of the post content, why would that change now? A look around gave me this `a.getCurrentPost()`, which returns a post object with a post title, but this will be the original post title, not the current post title, and doesn't get updated as the user edits the title A quick google however gave an identical Question with an indepth answer on stackoverflow: < const title = select("core/editor").getEditedPostAttribute( 'title' );
stackexchange-wordpress
{ "answer_score": 3, "question_score": 1, "tags": "javascript, wp admin, block editor, seo" }
Disable globally "Crop thumbnail to exact dimensions (normally thumbnails are proportional)" with Multisite I would like to disable the "Crop thumbnail to exact dimensions (normally thumbnails are proportional)" function for all blogs in my WordPress Multisite setup. This function is available in Dashboard, Settings/Media. The best solution would be PHP code in wp-config.php or simple plugin.
To disable cropping, insert this below code in `disable-automatic-image-crop.php` file in your mu-plugins folder: <?php /* Plugin Name: Disable Automatic Image Crop Author: Wordpress Community Description: */ add_action( 'init', 'czc_disable_extra_image_sizes' ); add_filter( 'image_resize_dimensions', 'czc_disable_crop', 10, 6 ); function czc_disable_crop( $enable, $orig_w, $orig_h, $dest_w, $dest_h, $crop ) { // Instantly disable this filter after the first run // remove_filter( current_filter(), __FUNCTION__ ); // return image_resize_dimensions( $orig_w, $orig_h, $dest_w, $dest_h, false ); return false; } function czc_disable_extra_image_sizes() { foreach ( get_intermediate_image_sizes() as $size ) { remove_image_size( $size ); } } ?> It's completely disabled automatic image cropping for all sizes.
stackexchange-wordpress
{ "answer_score": 1, "question_score": 0, "tags": "plugins, thumbnails, wp config" }
Add custom metabox to media library images Is it possible to add a custom meta box for the images of the media library?How I achieve this using `add_post_meta()` function?
Sure! Just follow this guide and make these changes: * Hook into the `add_meta_boxes_attachment` action instead of the `add_meta_boxes` action * In the `add_meta_box()` call, pass `'attachment'` as the `$screen` parameter * Hook into the `save_post_attachment` action instead of the `save_post` action And of course, make sure to customize the example code to your specific needs.
stackexchange-wordpress
{ "answer_score": 3, "question_score": 0, "tags": "images, metabox" }
Can't update or publish post/pages with browser Safari I have a very weird issue while trying to publish or update a post/page. Each time I try, I have the following error in the Gutenberg editor: "Update failed" or "Publish failed" depending the situation. The thing is that it only happens with the browser Safari on Mac. I tried with Chrome and Firefox, it works like a charm. Does anybody know this issue? I'm a Wordpress developer for a few years now and I never saw something similar. I'm using Wordpress 5.2.2.
I found the solution. I deleted the cookies of my website and it works. However I still don't understand why this issue happened.
stackexchange-wordpress
{ "answer_score": 0, "question_score": 0, "tags": "editor" }
Displaying field value in new column in users view on wordpress I have never developed a Wordpress site to this level before. One of my plugins introduces security questions for the user at registration time. I only have one question. In the backend, when admin role logged in, I want to display this meta data in a new column on screen in the users view. So: 1. Display extra column heading ‘Security Answer’ 2. For each user: `$data = get_user_meta ( $user_id); If $data[‘meta_key’] is ‘Xxxxx’ $answer = $data['meta_value'][0]; Display answer in new column` I don’t know how to go about this level customisation.
Use this function to register a new column in the users table: function users_custom_columns( $column ) { $column['security_answer'] = 'Security Answer'; return $column; } add_filter( 'manage_users_columns', 'users_custom_columns' ); And this function to display the new custom column: function display_users_custom_columns( $val, $column_name, $user_id ) { switch ($column_name) { case 'security_answer' : return get_user_meta( $user_id, 'meta_key', true); default: } return $val; } add_filter( 'manage_users_custom_column', 'display_users_custom_columns', 10, 3 ); You can place the code in your functions.php or in a custom plugin.
stackexchange-wordpress
{ "answer_score": 2, "question_score": 0, "tags": "user meta" }
Replace a character in all post titles and slugs I have hundreds of posts whose titles are of the form `XmY`, where `X` and `Y` are natural numbers, for example `18m324`. I'd like to replace `m` with `p` in all post titles and slugs, while keeping `X` and `Y` unchanged. How to do it in phpmyadmin? UPDATE wp_posts SET post_title = REPLACE(post_title, 'm' , 'p') WHERE post_type = 'post' AND post_status = 'publish'; This code should replace in the titles, but what about the slugs?
Slugs are saved in the very same table but in the `post_name` column. So your query would look like this: UPDATE wp_posts SET post_name = REPLACE(post_name, 'm' , 'p') WHERE post_type = 'post' AND post_status = 'publish'; By the way, I'd suggest you to use `$wpdb->posts` instead of just `wp_posts` ( then it would be compatible with different prefixes, but it's not important if it's just a "local" script )
stackexchange-wordpress
{ "answer_score": 1, "question_score": 0, "tags": "mysql, bulk" }
Is my code correct to enqueue CSS on a specific page? I am trying to load a CSS Stylesheet to ONLY the "about" page. I think I am 99% correct but what is wrong is the `plugins_url` \- to link to the theme folder where I keep my `CSS` can I just use simply: function testimonial_style() { wp_enqueue_style( 'custom_tooltip_frontend_css', url('path-to-my.css') ); } if(is_page( 42 )){ add_action('wp_enqueue_scripts', 'testimonial_style'); } Is it ok that I reference it with `add_action` and then "scripts" which is is is really a style **and not** a script...
Try this: I hope, It will works. **Explaination:** In below code in **"is_page( 42 )"** where 42 is page id of **about page**. So, if about page's id will be 42 then it's enqueue the stylesheet for that page only. Also I define particular path for this CSS file by using wordpress function **get_template_directory_uri()**. function testimonial_style() { if ( is_page( 42 ) ) { wp_enqueue_style( 'custom_tooltip_frontend_css', get_template_directory_uri().'/path-to-my.css' ); } } add_action('wp_enqueue_scripts', 'testimonial_style'); Let me know How it help you.
stackexchange-wordpress
{ "answer_score": 2, "question_score": 0, "tags": "functions, css, hooks" }
WordPress Dutch characters encoding problem I am using the Dutch special characters like ï and it is being converted to u00ef. I have tried ut8_unicode_ci in wp-config and in the database tables where the value is saved but it is still saved in the database as encoded characters. I want to display it as Dutch characters.
It Turns out the problem was with I was using json_enode to convert the data in to json before inserting it in to database and it was causing the encoding of the characters I have used `json_encode($url,JSON_UNESCAPED_UNICODE);` and now its working properly.
stackexchange-wordpress
{ "answer_score": 0, "question_score": 0, "tags": "mysql, encoding, characters" }
No url when downloading PDF I've a password protected webpage where uses can download PDFs. When clicking on the Download button, the PDF is uploaded by creating a URL, which works nice but that URL is then visible for everyone. How can prevent this and get the Download button ask for saving the PDF instead of opening a URL page. Is there a Plugin or another simple trick? I likely miss something. Thank you for your support, greetings from the Netherlands. Eric
See the answer here < , which involves sending headers with the appropriate values to cause the 'save as' dialog box to appear. That process will allow you to not provide the URL (which anyone can share), but provide the file (which people can share after they download).
stackexchange-wordpress
{ "answer_score": 0, "question_score": 0, "tags": "urls" }
Style Gutenberg metaboxes like they belong on the site When you add a meta box to Gutenberg, it looks different than the other items in the editor. There is a HR, and the fonts are different. ![enter image description here]( Does anyone know how to fix this so it looks like a natural part of the site, and not "some junk Automattic didn't add". Example code: function myMetaBox() { add_meta_box( 'MyMetaBox', "Why the odd font?", 'myBoxOutputCallback', 'post', 'side' ); } add_action( 'add_meta_boxes', 'myMetaBox' ); function myBoxOutputCallback(){ echo ("Gutenberg is a great addition! NOT!"); }
Bottom border (HR) can be removed using CSS: #__BLOCK_ID__.postbox:not(.closed) .postbox-header{ border-bottom: none; } p.s. change `__BLOCK_ID__` to first parameter used in `add_meta_box()` function.
stackexchange-wordpress
{ "answer_score": 1, "question_score": 1, "tags": "block editor" }
Timber: Get single image from media library with all attributes In my Timber-based theme, I'm getting a single image from the media library using the following (based on Timber/Image): <img src="{{ Image(678).src }}" alt="{{ Image(678).alt }}" srcset="{{ Image(678).srcset }}" sizes="{{ Image(678).img_sizes }}" /> However it's silly to repeatedly state the image id for each attribute. Is there a single command that can spit out a fully populated image instance or does this call for a custom PHP function, and make it available to Timber? * * * For reference, the above code outputs this: <img src=" alt="This is the image!" srcset=" 1052w, 150w, 300w, 768w, 1024w, 600w" sizes="(max-width: 1052px) 100vw, 1052px">
Ok, it's as simple as: {% set post_image = Image(678) %} <img src="{{ post_image.src }}" alt="{{ post_image.alt }}" srcset="{{ post_image.srcset }}" sizes="{{ post_image.img_sizes }}" /> Ref: Twig `set`
stackexchange-wordpress
{ "answer_score": 0, "question_score": 1, "tags": "theme development" }
Image editor is not loading For some strange reason the embed image editor is not loading ![image editor not loading]( 1. I've enabled debug in wp-config.php 2. I've disabled 100% of plugins and set a default theme 3. No errors either in Javascript console or the Apache2 error log 4. php-gd is installed 5. imagemagick is installed 6. php-curl is installed 7. I can discard a module missing in the server because I've installed another WP in the same server, and the image editor is working right. I'm out of ideas, not sure what can be causing this issue :(
Found the issue Checking in the related solutions I found this one Wordpress Image Editor not working - conflict? They were talking about a missing ?>, but obviously this was not related because I was using the default theme and not plugins. But suddenly remembered that I created a simple mu-plugin 10 days ago, and there was the problem: the ?> in the end of that mu-plugin.
stackexchange-wordpress
{ "answer_score": 2, "question_score": 0, "tags": "images" }
Increment paged on WP_Query What's the proper way to increment 'paged' under a WP_Query call? This is what I have below: $custom_query = new WP_Query([ 'post_type' => 'employee', 'post_status' => 'any', 'posts_per_page' => 10, 'paged' => 1, ]); foreach ($custom_query->posts as $employee) { var_dump($employee); } `var_dump($employee)` returns my first 10 records, but I can't figure out how to increment or target 'paged'. I've tried doing `$custom_query['paged']++;` but can't seem to get it to work.
You need to create a new `WP_Query` instance with the updated arguments. I will usually write it like this $args = [ 'post_type' => 'employee', 'post_status' => 'any', 'posts_per_page' => 10, 'paged' => 1, ]; $query = new WP_Query($args); while ($query->have_posts()) { // your logic goes here // foreach ($query->posts as $custom_stuff) {} // prepare for next loop iteration $args['paged']++; $query = new WP_Query($args); } When the first run is done, `$args['paged']` is updated and the `$query` variable is updated with a new `WP_Query` instance. if `$query->have_posts()` is true, the loop will then continue.
stackexchange-wordpress
{ "answer_score": 1, "question_score": 0, "tags": "php, posts, wp query" }
How to store ACF custom fields data in a custom table I am using the ACF Custom Fields plugin to store some info, but to my understanding, it is stored in the wp_postmeta table. Is it possible to store it in a custom table instead? So for example, the data would be: fullName, age, gender. and I would like to create a table called personalInformation and have these 3 columns.
It is possible to save ACF data in custom tables by using a separate paid plugin called ACF Custom Database Tables. However, if your goal is just to keep the database as light as possible, meevly.com's solution of creating your own custom metaboxes would be the lightest-weight option, versus adding two plugins just to track a few bits of data.
stackexchange-wordpress
{ "answer_score": 6, "question_score": 3, "tags": "plugins, php, database, advanced custom fields" }
Check if someone is editing a post (this content is currently locked) I'd like to create a kind of auditing. How can I check if an user is modifying an article? Is there a db query I can do to achieve this task? ![enter image description here]( I've found the following solution but I wonder if there is a native WordPress solution: <
Yes, there is a function in WP for that: `wp_check_post_lock()` Give it the post ID and it will return the user ID that is currently editing the post OR false if no one is editing the post (i.e. it is not locked). $is_locked = wp_check_post_lock( $post_id ); if ( false === $is_locked ) { // Post $post_id is not not locked for editing } else { // Post is not locked, $is_locked contains the user ID who is editing. $user = get_user_by( 'id', $is_locked ); echo 'Post id being edited by ' . $user->user_login; }
stackexchange-wordpress
{ "answer_score": 4, "question_score": 1, "tags": "plugin development, users, user access" }
Highlight active Admin Menu when added though add_menu_page I added a direct link to a page in the admin menu with the add_menu_page function. Once I click on the link, the About page edit screen opens, great. The problem though, i want the About menu item i added to be higlighted in blue. `add_menu_page( 'About1', 'About', 'edit_posts', 'post.php?post=87&action=edit', '', 'dashicons-editor-help', 7 );` ![enter image description here](
add_filter( 'parent_file', 'parent_file_hover' ); function parent_file_hover( $parent_file ) { global $pagenow; if ( $pagenow == 'post.php') $parent_file = "post.php?post={$_REQUEST['post']}&action=edit"; elseif($pagenow == 'post-new.php') $parent_file = "post-new.php?post_type={$_REQUEST['post_type']}"; return $parent_file; }
stackexchange-wordpress
{ "answer_score": 0, "question_score": 0, "tags": "admin, admin menu, add menu page" }
What does 'erase personal data' tool actually erase? What does 'erase personal data' tool actually erase? * User generated content (comments / posts/pages etc. if they can publish)? * Keep all data except user's name in comments? <
User generated content, including comments, are not deleted - the author name, email, IP address etc is simply anonymized so it can no longer be linked to that user. Nor is the user account account deleted - you would need to decide whether you wanted to do that manually or not. The Personal Data Eraser functionality has also been designed so it can be added to your custom plugins.
stackexchange-wordpress
{ "answer_score": 3, "question_score": 1, "tags": "privacy" }
has_category() for parent category Is there a way to make a condition for posts belonging to any sub-categories of a given parent category? Here is an example, assuming the following category structure: * News * FAQ * 1) Installing * 2) Using, etc. * Other if ( has_category( 'FAQ' ) ) { echo "This page has been updated for Quick Access Popup v10."; } else { echo "This page has NOT been updated for Quick Access Popup v10 yet."; } The has_category() condition includes only posts that are in the category 'FAQ' itself, but not those in its subcategories. I know I could use an array and list every categories but this is not convenient and need to be maintained when subcategories are added, removed, etc. The has_category() doc says nothing about parent categories (< Thanks.
To do what you want, you'll need to get a list of all the child categories of the category you want, and then check those. But you don't need to write that list manually. You can use `get_term_children()` to get the IDs of the child and grandchild categories: $cat_id = get_cat_ID( 'FAQ' ); $children = get_term_children( $cat_id, 'category' ); if ( has_category( $cat_id ) || has_category( $children ) ) { }
stackexchange-wordpress
{ "answer_score": 2, "question_score": 1, "tags": "categories, conditional tags" }
Query custom field with date I have a custom field that has a date picker. This date is in the format 11/12/2019. In my query I have the following: $meta_query = array( array( 'key' => 'date-available', 'value' => date("m/d/Y"), 'compare' => '<', ), ); This works in that it shows the posts where the custom date is less than the current date for this year and the December dates for this year don't show. But, for some reason the posts that have a date for 01/07/2020 still show. Anyone have an idea as to why?
According to the relevant article on the WordPress Codex, you _should_ be able to add a `type` argument to the meta array. Resulting in something like this: $meta_query = array( array( 'key' => 'date-available', 'value' => date("m/d/Y"), 'compare' => '<', 'type' => 'DATE' ), ); It's worth noting, though (as Gopalakrishnan18 mentioned), MySQL expects a date format of `Y-m-d`; so you **may** need to update the format of the date in the database.
stackexchange-wordpress
{ "answer_score": 0, "question_score": 1, "tags": "meta query" }