INSTRUCTION
stringlengths
11
999
RESPONSE
stringlengths
0
999
SOURCE
stringlengths
16
38
METADATA
dict
How to fetch woocommerce highest price and lowest price in custom template page? $max_query = new WP_Query( array( 'post_type' => 'product', 'post_status' => 'publish', 'orderby'=>'meta_value_num', 'order'=>'DESC','meta_key'=>'_price','posts_per_page'=>1) ); if(have_posts()){ while ($max_query->have_posts()){ $max_query->the_post(); $maxp = get_post_meta( get_the_ID(), '_price', true ); } I am using this and its worked perfectly but how to retrieve max or min price woocommerce without using wp query? actually I am using it for price range slider(dynamically).
This should do the job. $products = get_posts(array( 'post_type' => 'product', 'post_status' => 'publish', 'orderby' => 'meta_value_num', 'meta_key'=> '_price', 'posts_per_page' => -1, )); $highest = $products[array_key_first($products)]; $lowest = $products[array_key_last($products)]; $highest_price = get_post_meta( $highest->ID, '_price', true ); $lowest_price = get_post_meta( $lowest->ID, '_price', true );
stackexchange-wordpress
{ "answer_score": 0, "question_score": 0, "tags": "woocommerce offtopic" }
Wordpress wp_remote_post vs wp_remote_request I'm somehow new to Wordpress and its API and while writing an simple Rest Service to an remote Server i have been asked to use the native wp_remote_X functions. Right now i have some trouble to distinguish between them both: wp_remote_post() wp_remote_request(). Does it make any difference which one to use or is the wp_remote_request an alias to missing wp_remote_delete() and wp_remote_update() ?
You should be able to use both `wp_remote_request()` and `wp_remote_post()` for a 'POST' request, as they are just wrappers for the same `WP_Http::request` method that supports the methods: 'GET', 'POST', 'HEAD', 'PUT', 'DELETE', 'TRACE', 'OPTIONS', 'PATCH'. and the default one is 'GET'. The difference is that `wp_remote_post()` function has the 'POST' method explicitly set via `WP_Http::post` that's also a wrapper for `WP_Http::request`.
stackexchange-wordpress
{ "answer_score": 4, "question_score": 2, "tags": "wp remote post, wp remote request" }
WP Multisite - Additional subdomain on the site for API purposes We have WP multisite network with WooCoomerce shops. All the network is served through Cloudflare CDN. Our ERP is accessing WooCommerce API of each website in the WP network. Since there so many, calls we are getting 503 from Cloudflare. It's not a server problem. It's a problem of too many requests to Cloudflare. So what I would like to have is a separated subdomain (example: api.domain.com) for each domain in the network. That subdomain will not be proxied thru Cloudflare. How to do I do that? How can I add an additional subdomain to a site on WP multisite network?
I have resovled it myself. I have enabled sunrise in wp-config. Then add a script to sunrise.php to override HTTP_HOST. I made it dynamic since we have many websites. When you visit api.domainxy.com it automatically shows you domainxy.com. <?php $re = '/(?:api\.)(.*)/m'; $str = $_SERVER['HTTP_HOST']; preg_match_all($re, $str, $matches, PREG_SET_ORDER, 0); if ($matches && $matches[0][1] != "") { $_SERVER['HTTP_HOST'] = $matches[0][1]; } ?>
stackexchange-wordpress
{ "answer_score": 2, "question_score": 0, "tags": "multisite, api, cloudflare" }
Thumbnails generated from PDF in the "Media" section - how to show them in theme template? I have an ACF custom field for "File". It allows users to upload PDF files of some reports. In the Media section in WP Admin, I can see that the PDF we upload auto-generates the thumbnails. On the frontend, in my theme for the website, when I try to see the files array from the custom field, there's nothing related to the file that contains its thumbnail. Is there some way I can access the thumbnail for the PDF? I know I can generate this myself using imagick or GD, but I'd like to leverage what WP has already done.
To get the attachment's icon, you can use `wp_get_attachment_image()`. For example, let's say I've uploaded a Word doc and it's got the ID `1234`: // Parameter 3 - 'true' - tells WP to treat this as an icon. $img_tag = wp_get_attachment_image( 1234, 'thumbnail', true ); // $img_tag contains: // <img width="48" height="64" // src=" // class="attachment-thumbnail size-thumbnail" // alt="" loading="lazy" // />
stackexchange-wordpress
{ "answer_score": 3, "question_score": 1, "tags": "advanced custom fields, media" }
Scope for PHP Variables Assigned in functions.php or a plugin I'm a web developer who works on WordPress sites and want to ensure I keep PHP variables out of the global scope. I have questions about this: 1. If I created a `$new_title = "test seo title";` variable in an active theme's **functions.php** file, is that `$new_title` variable accessible (not undefined) in the active theme's PHP files? Is that variable also accessible in the active plugin files? 2. Also, if I created a `$new_title2 = "test seo title2";` variable inside an active plugin, is that `$new_title2` variable accessible (not undefined) in active theme's **functions.php** file and other theme PHP files?
Nope! There is no way. variable scope is file based in PHP, It means you can't access a variable or even function and class from another file unless you include that file inside current file or use other similar ways like namespace or API call to get desired value from the file. you can read more about variable scope in PHP: <
stackexchange-wordpress
{ "answer_score": 2, "question_score": 1, "tags": "plugins, php, plugin development, functions" }
How to manage same slug posts suffix method? domain.tld/post-name | post_id = 5 and domain.tld/post-name-2 | post_id = 77 The above scenario is the solution brought by wordPress. Let's complicate this a bit and add it as a prefix for example or timestamp etc. If we want to add something, how do we do it?
Developers can use the following filter: /** * Filters the post slug before it is generated to be unique. * * Returning a non-null value will short-circuit the * unique slug generation, returning the passed value instead. * * @since 5.1.0 * * @param string|null $override_slug Short-circuit return value. * @param string $slug The desired slug (post_name). * @param int $post_ID Post ID. * @param string $post_status The post status. * @param string $post_type Post type. * @param int $post_parent Post parent ID. */ $override_slug = apply_filters( 'pre_wp_unique_post_slug', null, $slug, $post_ID, $post_status, $post_type, $post_parent ); It is then the programmer's responsibility to ensure uniqueness of the slug.
stackexchange-wordpress
{ "answer_score": 2, "question_score": 1, "tags": "slug" }
WordPress custom taxonomy not showing I have a simple custom Taxonomy register_taxonomy( 'categories', array('career'), array( 'hierarchical' => true, 'label' => 'Departments', 'singular_label' => 'Department', ) ); and I am trying show a list of the Taxonomy like so .. $terms = get_terms( array( 'taxonomy' => 'career', 'hide_empty' => false, ) ); if ( ! empty( $terms ) && is_array( $terms ) ) { foreach ( $terms as $term ) { ?> <a href="<?php echo esc_url( get_term_link( $term ) ) ?>"> <?php echo $term->name; ?> </a><?php } } ?> yet nothing is displaying, I have been over and over for a few hours and cant see the problem, can anyone see why this is not displaying ? Thank you
$terms = get_terms( array( 'taxonomy' => 'career', 'hide_empty' => false, ) ); Your taxonomy isn't called `career`. Your taxonomy is called (confusingly) `categories`. If you check the docs, you'll see the second argument passed to `register_taxonomy` is the object type (eg, `post`, `my_cpt`) that the tax is to be used on. So in your registration you are creating a taxonomy called `categories` that will be used on the `career` post type.
stackexchange-wordpress
{ "answer_score": 2, "question_score": 0, "tags": "plugins, custom post types, php, custom taxonomy" }
How to get a random single category name in get_posts()? How can I get a random category name one at a time?? The post may have multiple category instead of a single category. I just want to show a single category name in the post grid loop. $home_blog_posts = get_posts(array( 'posts_per_page' => 3 )); Thanks.
You can use `wp_get_post_categories` to get the categories from your posts. Then you can use `array_rand` to get one random category from that array. Check out these links on how to use `wp_get_post_categories` and `array_rand` to suit your needs: < <
stackexchange-wordpress
{ "answer_score": 0, "question_score": 0, "tags": "theme development, query, get posts" }
How to display already created menus via php? So I have a couple of already created menus on my wordpress installation. What I am planning to do is display navigation menus in a sliding popup. I have tried using wp_nav_menu() but it always shows the first (alphabetically) menu instead of the one I want displayed. $args = array ( 'menu_id' => $short, 'menu_class' => 'menu', 'fallback_cb' => false ); wp_nav_menu( $args); $short is getting the menu name from the URL. As far I have understood the wp_nav_menu function I need to add code to the functions.php as well. Is that correct? I feel like in my usecase that's not the best way to solve the problem, as I want to create 25 sliding navs via PHP. If I have to add code to the functions.php as well for each menu I can do the whole task manually. Thank you
I found the solution. I had to do the following $args = array ( 'theme_location' => $short, 'menu_id' => $short, 'menu_class' => 'menu', 'menu_id'=>$menu_id, 'fallback_cb' => false ); wp_nav_menu( $args); Theme location was the correct attribute.
stackexchange-wordpress
{ "answer_score": 0, "question_score": 0, "tags": "php, functions, menus" }
How to add code to `head` with WordPress 5.9 FSE (Full Site Editing) Like adding Google Analytics code, and some other things surrounding the `<head>` tag, how's all this done in FSE as there's no `header.php`? Should I use `functions.php` for everything? (Also can somebody make a fse tag in stackexchange?)
As far as I understand the `wp_head` and `wp_footer` actions should still work under FSE in WP 5.9+, through the template canvas PHP file that's loaded through the `locate_block_template()`. That PHP file contains the basic HTML structure and there we find e.g. the familiar `wp_head()` and `wp_footer()` function calls that we usually had in the old `footer.php` and `header.php` theme files. The current block template HTML from `get_the_block_template_html()` is now displayed within the body tag from the template canvas. So in FSE use e.g. the theme's `functions.php` file or a custom plugin to add your `wp_head` and `wp_footer` actions in PHP.
stackexchange-wordpress
{ "answer_score": 6, "question_score": 4, "tags": "block editor, full site editing" }
using is_paged for hiding image on posts In my posts I'm using `<!--nextpage-->` in order to paginate specific blog posts, which works fine. But my issue is that the featured image shows in the post header for each page. I've tried using `!is_paged` but it's not working and I read that it doesn't work for posts using `<!--nextpage-->` The code I'm using: if (isset($props['featured_in_head'])) { if ( !is_paged() ){ $props['featured'] = $props['featured_in_head']; } } I've noticed on the sub-pages of this one post that my body has the classes of `single-paged-2` or `paged-2`, but it doesn't look like it has just the paged class, so if there's a way to hide `.featured` via CSS I could just do that Any help is appreciated
> I read that it doesn't work for posts using `<!--nextpage-->` Not necessarily, but basically, if the current URL ends with `/page/<number>` as in ` and ` then `is_paged()` would work, i.e. it returns `true` on page 2, 3, etc. But for singular posts with a page break, i.e. the `<!--nextpage-->` tag, where the URL normally ends with `/<number>` as in ` then `is_paged()` would return a `false`. However, you can use `get_query_var( 'page' )` (or the global `$page` variable) to get the page number and then render the featured image only if the page number is 1 or < 2. So for example, just replace the `!is_paged()` in your `if` with `(int) get_query_var( 'page' ) < 2`, and then that image would no longer appear on page 2, 3 and so on.
stackexchange-wordpress
{ "answer_score": 2, "question_score": 0, "tags": "posts, pagination, paged" }
Separating publish date and last modified Am I correct in understanding that the publish date and the modified date are actually the same thing under the covers in WP? We have a need to show “this article was last updated on”, which could be 2018 December. But the edit to put this date in our content could be done today, in April 2022. If we change the official modified date to be shown to the world (2018), by changing the publication date in WP, it doesn’t work as it always updates internally the modified date today and the sorting order even by “publish date” seems to reflect the modification today instead of the 2018 days I put in that article. Am I doing something wrongly? How can we put in a custom publication date in the last while still retaining that this modification was done today? I’ve tried using “modified” and “publish_date” in the WP Query and the results are confusing.
The publish date is either when the post is originally published, or the date that you choose to set it as published in the Editor, so that is the part you can manually control. The modified date is whenever an update has most recently occurred, such as when the Update button is pressed in the Editor. You might end up wanting to add a custom field to hold a "public date." The downside there is it would be stored in postmeta, making your queries less performant. Another alternative would be adding custom code that adds a date control in the Editor and forcibly sets the modified date to whatever you are choosing manually.
stackexchange-wordpress
{ "answer_score": 1, "question_score": 0, "tags": "date time" }
WordPress wp_localize_script nonce and ajax URL I'm making an Ajax call in an Elementor site, and I'd like to use a nonce while doing it. Since my code is really simple, I didn't create a new JS file for it placed in Elementor's HTML widget, and I handle the request in the `functions.php` file. I realized that the best way is to use `wp_localize_script` to make both the nonce and the Ajax URL available in the client side, but the function is asking for a file to register, and I don't know how to approach this, since there is no file to register and enqueue, `functions.php` is probably already enqueued? How is it done? I've already read through so many tutorials and still didn't find that answer. Any knowledge will be of great help. Many thanks.
`wp_localize_script()` doesn't care much which script handle you use as long as it is a valid one. You could use your theme's or Elementor's main script handle with the function to make the data available for your script. You'll need to check your theme's or Elementors source coude to find what these handles are. **Side note:** It says on More information on the documentation that it is nowadays recommended to use `wp_add_inline_script()` to provide data to scripts as > _`wp_localize_script()` should only be used when you actually want to localize strings._
stackexchange-wordpress
{ "answer_score": 1, "question_score": 1, "tags": "ajax, nonce, wp localize script" }
Updated MAMP and localhost on MacOS site no longer accessible I have tried to access my site on localhost:8888/ and it no longer loads with any formatting since updating MAMP to a newer version. I am able to access the db through phpMyAdmin but not sure what is what. There is no back-up either since it was on a local machine (my bad!). This whole issue arose when someone asked if "I could view the site somewhere other than your computer at my leisure". After a few google searches and trying quite a few solutions, which did not work, I've lost my ability to log-into this site and make any changes or even view it.
When you upgrade MAMP, it will preserve the existing installation to a folder that is called MAMP_current-date, something like MAMP_2022-04-14_08-00-00 (the last bit is a time stamp). You can revert to the previous version by renaming the current MAMP folder (under the Applications folder) or delete it, then rename the previous version with the date and time stamp appended to just MAMP. Then restart the MAMP services to see if you can access your WP site.
stackexchange-wordpress
{ "answer_score": 0, "question_score": 0, "tags": "wp admin" }
Why is my Javascript console showing a 404 error for a file called "null" on a clean Wordpress install? Every Wordpress site I am building shows _404 (Not Found)_ error in the Javascript console for a file called _null_. I have confirmed that this happening on a clean install of WP 5.9.3 without any plugins, settings changes, or database edits. Here's what it looks like in Chrome Dev console: ![screenshot of javascript console 404 error for null]( This happens on every page on the site whether I am logged in or not. In the above example, if you look at the referenced line 330, it's always a blank line at the end of the rendered HTML: ![the supposedly bad line of code]( What is causing this error?
Turns out this was being caused by a Chrome browser extension. I use an extension installed called "CrxMouse Chrome Gestures." This extension is the cause of this error. I have turned off the extension and notified the author of this bug.
stackexchange-wordpress
{ "answer_score": 2, "question_score": 1, "tags": "404 error" }
Does an administrator access allow someone to access to the WordPress database? I gave an administrator access to a developper and he made a copy of my entire Wordpress website (meaning : files from my FTP and the whole database). How did he succeed to do that ? Does creating an administrator role grant access to the whole FTP and the mysql database ?
No, `wp-admin` Administrator access does not grant direct access to files or the database. However, as an Administrator, you can install / activate / use / deactivate / uninstall plugins, and there are a number of plugins which can take backups of the files and the database. So, anything WordPress has access to, they would have access to.
stackexchange-wordpress
{ "answer_score": 1, "question_score": 0, "tags": "admin, mysql" }
Custom PHP script throws critical error ONLY when editing page I have the following script added to _functions.php_ in my **child** theme: function getlatestfile() { $iterator = new RecursiveIteratorIterator(new RecursiveDirectoryIterator('wp-content/uploads/cams/')); foreach ($iterator as $file) { if ($file->isDir()) continue; $path = $file->getPathname(); } return "<img src=' . $path . "' />"; } // register shortcode add_shortcode('getfieldimage', 'getlatestfile'); I can save the code, insert the shortcode `[getfieldimage]` on the page, and the page **indeed displays** the latest image. No complains. But when trying to edit again the page containing the shortcode, WP tells me that there's a critical error, and wants me to go to < . Cannot get any helpful info there.
ABSPATH helps to display the page in the backend in editmode. But for the frontend, the path for the `<img../>` tag needs to be modified. `cutprefix()` function (taken from here) does the job. This is the working solution for the front- and backend: function getlatestfile() { $iterator = new RecursiveIteratorIterator(new RecursiveDirectoryIterator( ABSPATH . 'wp-content/uploads/cams' )); foreach ($iterator as $file) { if ($file->isDir()) continue; $path = $file->getPathname(); } $path = cutprefix($path, '/home/username/web/mysite.url/public_html/'); return("<img src=' . $path . "' />"); } function cutprefix($str, $prefix){ if (substr($str, 0, strlen($prefix)) == $prefix) { $str = substr($str, strlen($prefix)); } return $str; } Thanks to Pat J for leading me in the right direction.
stackexchange-wordpress
{ "answer_score": 0, "question_score": 0, "tags": "php, scripts" }
add class to element if user is not logged in Please help . I need to add class to this button if user is not logged in <?php echo apply_filters( 'my_order_html', '<button type="submit" class="ADD-CLASS-HERE cfw-primary-btn cfw-next-tab validate" name="my_list_html" id="place_order" formnovalidate="formnovalidate" value="' . esc_attr( $order_button_text ) . '" data-value="' . esc_attr( $order_button_text ) . '"><span class="cfw-button-text">' . esc_html( $order_button_text ) . '</span></button>' ); // @codingStandardsIgnoreLine ?>
You can try something like this and implement it in your own case <?php if ( is_user_logged_in() ) { $extraClass = "hide-button"; } else { $extraClass = ""; } ?> <a class="<?php echo $extraClass;? href="#">">Button text</a> and give the new class a styling like "display: none;" or something
stackexchange-wordpress
{ "answer_score": 0, "question_score": 0, "tags": "users, login, session, logout" }
Can we use a webservice with Wordpress? Assuming that my site uses a database through the web service to fetch content, style and other things for my site. Can we make this connection in a way provided by the CMS? A plugin does that? Should we do it ourselves? Thanks for answers.
The answer to the current question is found. Thank you all for your answers. The answer to the question is 'yes'. We can use an external webservice/API in the Wordpress code. We can use for this, wp_remote_request to call through an URL. For my part, I did otherwise because my webservice is a special one, so I created a SoapClient class in the files of my plugin to make the connection and the function calls. To provide a correct display of the webservice, I decided to use 2 widgets. 1 for the search and 1 for the display. I still have some problems with the display with the web page but that will be another issue. Thanks again.
stackexchange-wordpress
{ "answer_score": 0, "question_score": 1, "tags": "plugins, plugin development, templates, content, web services" }
How to get an attachment id from a filename I have not been able to find a reliable solution for how to lookup the id for attachments in the media library from a filename as Wordpress does not appear to provide such a function. Most solutions rely on searching the GUID field in various tables, however there are issues with attachments uploaded with greater than 2560px resolution. Wordpress appends '-scaled' to the filename returned by functions like get_attached_file(), but this is not reflected in the guid database column. I'd be grateful for a generic function that returns the attachment id when given a filename.
I worked this out eventually by tracing through the code for get_attached_file() to see where it was getting the filename from, and reverse engineered the following: function get_attachment_id_by_filename($filename) { global $wpdb; $sql = $wpdb->prepare("SELECT * FROM $wpdb->posts WHERE post_type = 'attachment' and guid like %s order by post_date desc", "%$filename"); $attachments = $wpdb->get_results($sql, OBJECT); return $attachments[0]->ID ?? false; } Note that it is possible the query will return more than one row if the same file basename exists in different media library folders. This routine will however only return the most recent found. This works for everything I can throw at it so far, but welcome any issues people may be aware of with this solution.
stackexchange-wordpress
{ "answer_score": 2, "question_score": 1, "tags": "functions, attachments" }
wpdb get_results() and prepare when to use prepare? so if i have a function that gets terms from the database ( not the user ) do I need to use prepare first ( before get_results() ), or some sort of data sanitizing?
> so if i have a function that gets terms from the database ( not the user ) do I need to use prepare first ( before get_results() ), or some sort of data sanitizing? Yes, but you should be using `get_terms`/`WP_Term_Query`/`wp_get_object_terms`/etc and the other term APIs instead as they're safer and can be much faster. SQL bypasses object caches and performance plugins, as well as local caches, bulk fetches and security protections. If you're going to perform an SQL query though, don't try to escape it, use `prepare` to insert variables into the query ( never do it directly! ): $safe_sql = $wpdb->prepare( "SELECT * FROM `table` WHERE `column` = %s AND `field` = %d OR `other_field` LIKE %s", [ 'foo', 1337, '%bar' ] ); **Remember, if you need to use an SQL query on the core WordPress tables, there's a high chance you've done something wrong or don't know about a function that does it for you.**
stackexchange-wordpress
{ "answer_score": 2, "question_score": 1, "tags": "wpdb, sanitization" }
Use custom image size in admin panel I have add some image size like: add_image_size( 'custom-small', 600, 600 ); add_image_size( 'custom-medium', 1280, 1280 ); add_image_size( 'custom-large', 2560, 2560 ); and I have removed all the default sizes. Now the Media Library in the Admin panel is loading full image instead of medium. Is it possible to specify a custom size to use?
Image sizes are hard-coded throughout WordPress core; Tom's comment to adjust the dimensions of the built-in image sizes is the best approach.
stackexchange-wordpress
{ "answer_score": 0, "question_score": 1, "tags": "uploads, media library, media modal" }
Woocommerce inventory I'm working on woocommerce project and I need to check inventory status via external API before I create order. It is a cash register system in physical store that I can't change. I'm using > woocommerce_checkout_order_processed hook to add my logic here but I'm not sure how can I prevent order from saving if invenotry over API changed in meantime. So the flow I need here is: * User wants to buy 10 items, adds them to cart * User clicks 'Place Order' * hook is activated * api is triggered and it returns that only 5 are available at the moment * show message and don't save order
The `woocommerce_checkout_order_processed` hook is too late. The order has already been created. You'd probably want to hook into `woocommerce_after_checkout_validation` so that you can check for the inventory before the order is even triggered and set an error that will be displayed at checkout. By hooking in here, you will be able to short circuit the order creation with the error notice. You can find more details about this in the `WC_Checkout` class. See: <
stackexchange-wordpress
{ "answer_score": 1, "question_score": 0, "tags": "plugin development, woocommerce offtopic" }
Custom Fields - How to create a list from multi-line entries of a single value If I have the following name/value pair for a custom field.... ![enter image description here]( ...is there a PHP loop process I can apply that will allow me to display them on the front-end as individual values because there is a line-break between each item? or do **I have to** create multiple name/value pairs for each item? The end goal in my case is to create a list on the front end of these items that are being pulled from this value area. Thanks for any tips!
Yes, grab the value via `get_post_meta`, then it's just a matter of generic PHP loops and string manipulation. Try using the `explode` function with `\n` as the separator to create an array you can loop through. You may need to check for empty values since some of your lines are blank, but the `get_post_meta` part is the only part of this question that requires WordPress knowledge: $data = get_post_meta( $post_id, 'What Responsibilities Will I have?', true ); $lines = explode( '\n', $data ); // now do things with the $lines array
stackexchange-wordpress
{ "answer_score": 3, "question_score": 0, "tags": "custom field, loop" }
Where is this text in a wordpress email coming from? Want to change/remove I vaguely remember adding this text somehow ("Thank you for trying our product. We hope it brings you joy.") during some late night coding session. However, I've since forgot and want to remove it very much. I've looked all through the settings and can't find where it was added. Please advise! ![picture of my order complete email](
That looks like an order note for the specific product. Check the order notes under advanced when editing the product.
stackexchange-wordpress
{ "answer_score": 0, "question_score": 0, "tags": "woocommerce offtopic" }
How to remove the two duplicate values How to remove the two duplicate values Example I have the variable 1 $help_brother: $help_brother = '30,45,12,13,14,15'; And the variable 2 Force World: $force_world = '45,12,15'; The result must be: Result: `'30,13,14';` Any help is welcome. Thanks in advance.
Here is the result $help_brother = '30,45,12,13,14,15'; $force_world = '45,12,15'; $help_brother_array = explode(',', $help_brother); $force_world_array = explode(',', $force_world); $Result = array_diff($help_brother_array, $force_world_array); echo implode(",",$Result); You can get the following result. If it helps then upvode the answer.
stackexchange-wordpress
{ "answer_score": 0, "question_score": 0, "tags": "php" }
how to get serialized post meta I have posts that have video content and these videos stored in database like this (serialized) `a:1:{s:9:"video_url";s:0:"";} ` This serialized data have post video urls but can not get this data. I used `<?php echo get_post_meta(get_the_ID(), '_custom_field', TRUE); ?>` But this get_post_meta display output "array" instead of video urls
`get_post_meta()` with the 3rd parameter set to `true` will return a single item with the key specified in the 2nd parameter (`_custom_field` in your code). If this item is an array, it'll return as the array. In your case, it appears that the data is: array( 'video_url' => '', ) ...which is why, when you try to `echo` it, it's printing `Array` to the screen. I'd suggest something more like this: <?php $meta = get_post_meta(get_the_ID(), '_custom_field', TRUE); echo $meta['video_url']; ?> ...or, if you're expecting multiple `video_url`s, you could do this: <?php $meta = get_post_meta(get_the_ID(), '_custom_field'); foreach ( $meta as $item ) { echo $item['video_url']; } ?> (Note that it also appears that, in the metadata you've posted, there's an empty value for the actual `video_url`, but I can't say what might have caused _that_.)
stackexchange-wordpress
{ "answer_score": 1, "question_score": 0, "tags": "php, custom field, post meta, wpdb, phpmyadmin" }
Gutenberg Editor: dynamically edit slug field based on ACF field I'm trying to edit the `slug` field on the right panel of Gutenberg editor and edit its content based on a custom field. I noticed that I can access the field by using this JavaScript to interact with the React Component: `wp.data.select('core/editor').getEditedPostSlug();` My question is: How can I edit this field in JavaScript? There's no `.setEditedPostSlug()` method for this and select the field in normal JS script is impossible because the field's ID is generated each time the panel is opened and if we close the panel, the field disappear from the DOM.
I've found the way to edit the slug's field. Just simply use: wp.data.dispatch('core/editor').editPost({slug: 'my-slug-value-here'}); With an event listener like this, I can dynamically change the slug field based on a custom field: jQuery(document).ready(() => { const acfField = 'field_61f8bacf53dc5'; const inputShortTitle = document.getElementById('acf-' + acfField); const slugify = (str) => { return str.toLowerCase().replace(/ /g, '-') .replace(/-+/g, '-').replace(/[^\w-]+/g, ''); } const updateSlug = () => { wp.data.dispatch('core/editor').editPost({slug: slugify(inputShortTitle.value)}); } if (inputShortTitle !== null) { inputShortTitle.addEventListener('input', () => updateSlug()); } });
stackexchange-wordpress
{ "answer_score": 1, "question_score": 1, "tags": "permalinks, javascript, block editor, slug" }
Admin slow on Postlist (over 30k Posts in Database) we have a Site with around 20k Posts in the normal postlist and another 10k in other CPT. The custom post types work really fast, but the normal Post List doesn't. I assume that might be because the server aggregates how many posts are published, how many are mine and how many are deleted, but I'm not really sure about that. Any idea how to limit what is being queried - I looked in google how to remove sections from the query but all I find is css "hacks" to not display the filters, not how to remove them from the query. if you have any other ideas, please let me know.
Perhaps this filter can help you to modify the query for the specific post type and inside wp-admin as per the documentation, this filter is called before the query is executed so you can modify/optimize the query with the help of this filter. do_action_ref_array( 'pre_get_posts', WP_Query $query ) further reference: <
stackexchange-wordpress
{ "answer_score": 0, "question_score": 0, "tags": "custom post types, posts, wp admin" }
Display parent page URL for child page I have this code that is working but is giving me the wrong link gives me this link `example.com/index.php/sample-page/` but I need this link `example.com/sample-page/` <?php global $post; if ( $post->post_parent ) { ?> <a href="<?php echo get_permalink( $post->post_parent ); ?>" > <?php echo get_the_title( $post->post_parent ); ?> </a> <Br><?php echo get_permalink( $post->post_parent ); ?> <?php } ?>
`$post->post_parent` returns 0 when there's no parent associated. You need to check if the value is greater than 0. <?php global $post; if ( $post->post_parent > 0 ) { ?> <a href="<?php echo get_permalink( $post->post_parent ); ?>" > <?php echo get_the_title( $post->post_parent ); ?> </a> <Br><?php echo get_permalink( $post->post_parent ); ?> <?php } ?> Also, check your permalink settings URL base.
stackexchange-wordpress
{ "answer_score": 0, "question_score": 0, "tags": "permalinks" }
Newly created user role not displaying on users screen I have created a new role with the following code: add_role('sponsored_content', 'Sponsored Content', get_role('contributor')->capabilities); I have added users to this role. When viewing the users screen this **Sponsored Content** role does not display. ![Users screen not displaying the custom sponsored content role]( Using the browser inspect tool the markup is present: <li class="sponsored_content"><a href="users.php?role=sponsored_content">Sponsored Content <span class="count">(6)</span></a> |</li> There is styling coming from a "constructed stylesheet" preventing it from displaying: .sponsored_content { display: none !important; } This is not styling that I have added and I do not know where it is coming from. Any ideas where this styling is coming from or how to remove it?
The constructed stylesheet was coming from the browser, in this case Brave Browser. The ad blocking feature added this styling. Turning shields off fixed the issue.
stackexchange-wordpress
{ "answer_score": 0, "question_score": 0, "tags": "wp admin, users, admin, user roles" }
Contact form 7 Hide response messages after 5 seconds I just installed this plugin and I must say it does everything I need. I am using a custom made popup div with a CF7 inside it. I need to hide response messages (error, success message) after 5 seconds. Is that possible?
you can use below code to hide message // Contact Form 7 submit event fire document.addEventListener('wpcf7submit', function(event) { setTimeout(function() { jQuery('form.wpcf7-form').removeClass('sent'); jQuery('form.wpcf7-form').removeClass('failed'); jQuery('form.wpcf7-form').addClass('init'); }, 1000); }, false);
stackexchange-wordpress
{ "answer_score": 2, "question_score": 1, "tags": "ajax, plugin contact form 7" }
Changing labels of status filters for post grid Is there a way to change filter labels for custom post type? For example, change `Drafts (2)` to `Disabled (2)` without localization plugins like Loco Translate? ![enter image description here]( I've tried `apply_filters( "views_{$this->screen->id}", $views );` filter, but array already contains links with html. Regex doesn't looks "the right way". Array ( [all] => <a href="edit.php?post_type=sha-wlc" class="current" aria-current="page">All <span class="count">(13)</span></a> [publish] => <a href="edit.php?post_status=publish&#038;post_type=sha-wlc">Published <span class="count">(11)</span></a> [draft] => <a href="edit.php?post_status=draft&#038;post_type=sha-wlc">Drafts <span class="count">(2)</span></a> [trash] => <a href="edit.php?post_status=trash&#038;post_type=sha-wlc">Trash <span class="count">(1)</span></a> )
Here's an untested way to override it, based on my older answer: add_action( 'init', function() { $vars = get_object_vars( get_post_status_object( 'draft' ) ); $vars['label_count'] = _n_noop( 'Disabled <span class="count">(%s)</span>', 'Disabled <span class="count">(%s)</span>', 'wpse-domain' ); register_post_status( 'draft', $vars ); }, 1 ); We use the priority 1, since the default `draft` status is registered at priority 0. You might look into the `$vars['label']` as well.
stackexchange-wordpress
{ "answer_score": 1, "question_score": 1, "tags": "plugins, plugin development" }
How to assign php file(template) to several pages with same prefix page name/slug Can I assign WP php file (specific template) to several pages with same prefix name/slug using (`if is_page(){}`) ? If it's possible it could be useful. Is there a php function to do like css selector : `[class*="activity-"]` for example ??: `if(is_page('[activity-]')){ include "activity.php"; }` the goal is to not repeat 4 times the same function : `if(is_page('activity-sport')){ include "activity.php"; } ` `activity.php` assign to : * `website/activity-sport` * `website/activity-culture` * `website/activity-charity` * `website/activity-work`
How about this? For PHP 8 (faster) if ( str_contains( get_post_field( 'post_name' ), 'activity') ) { get_template_part( 'activity' ); } For older versions of PHP if ( strpos(get_post_field( 'post_name' ), 'activity') !== false ) { get_template_part( 'activity' ); }
stackexchange-wordpress
{ "answer_score": 0, "question_score": 0, "tags": "functions, pages, slug" }
Use current class method inside add_submenu_page() I have a class like below. namespace Inc\Admin; class Admin { public function __construct() { add_action('admin_menu', [$this, 'admin_menu']); } public function admin_menu() { add_submenu_page('sports_info', 'Sports Information', 'Sports Information', 'manage_options', [$this,'sports_info_page'], [$this, 'html_page']); } public function html_page() { //some code } public function sports_info_page() { //some code } } I am getting below errors. Fatal error: Uncaught Error: Object of class Inc\Admin\Admin could not be converted to string Error comes from `[$this,'sports_info_page']` of `add_submenu_page()`.
You're getting that error because the 5th parameter for `add_submenu_page()` should be a string which is the menu slug and yet you supplied a callback (`[$this,'sports_info_page']`). So be sure to use a valid slug like so and the error will be gone: add_submenu_page( 'sports_info', // parent slug 'Sports Information', // page title 'Sports Information', // menu title 'manage_options', // capability 'your-menu-slug', // menu slug [$this,'sports_info_page'] // callback );
stackexchange-wordpress
{ "answer_score": 1, "question_score": 0, "tags": "plugins, sub menu" }
How to pass multiple parameter in add_action() I have below code. add_action( 'admin_init', [$this, 'settings_page_registration'] ); I would like to use `enqueue_assets` function name inside `add_action()`. Should I use like below ? add_action( 'admin_init', [$this, 'settings_page_registration', 'enqueue_assets'] );
If you need to call `enqueue_assets` at `admin_init`, then add a new `add_action()`: add_action( 'admin_init', [$this, 'settings_page_registration'] ); add_action( 'admin_init', [$this, 'enqueue_assets'] ); * < That said, if your assets are JS scripts or CSS, you should consider `wp_enqueue_script()` & `wp_enqueue_scripts` * < * <
stackexchange-wordpress
{ "answer_score": 2, "question_score": 0, "tags": "admin, actions" }
Admin Panel Development How to create Tab on Admin Panel like "General Settings" screenshot ? How to create List on Admin Panel like "Pages" screenshot ? ![General Settings]( ![Pages](
1. This would be a good place to start. `add_menu_page`. 2. The posts list are automatically created when you register a new CPT. You can, however, create anything in a custom menu page (read the docs from point 1).
stackexchange-wordpress
{ "answer_score": 1, "question_score": 0, "tags": "admin" }
*Just curious* I erroneously used hook add_action() instead of add_filter() and there was no error and the result was correct. Why is that? While working on a project I used the incorrect hook type `add_action()` which does not exist, yet there was no error notice and the correct result returned. I only realized it was wrong while searching for the method along with the `$hook_name` name in the package and it was not found, and when I checked the code reference page, it showed that it is `add_filter()`. Why does it still work?
`add_action()` uses `add_filter()` behind the hood. function add_action( $hook_name, $callback, $priority = 10, $accepted_args = 1 ) { return add_filter( $hook_name, $callback, $priority, $accepted_args ); } Source: < So basically it doesn't matter if you use add_filter or add_action. But it doesn't mean you should, using the appropriate function for a event will make your code easier to follow and understand, if you always use add_filter or add_action for every single event it can create a lot of confusion.
stackexchange-wordpress
{ "answer_score": 6, "question_score": 2, "tags": "codex" }
How can I create a custom page for this error? How can I create a custom page for this too many connections error page because I know it's because my server is overloaded? I wanted to show a custom error page instead of this when my website is overloaded by traffic. ![This is the Error Page.](
Check out the source of `dead_db()` which powers the message. You'll see that you can create a file `db-error.php` in your WP content directory (which by default is `/wp-content/`) and it'll load that instead!
stackexchange-wordpress
{ "answer_score": 2, "question_score": 2, "tags": "errors" }
Can we intercept user_login and user_pass from a wp_login_form? with my plugin, I have a login form. I use the wp_login_form() function of Wordpress. As you know, this function links to the wp-login page. But if the user_login is not present or if the email is empty in the database, an error will be present. My users come from an external database. Imagine the following situation: A user from my external database connects for the first time on the site, so he is not in the wp_users table of Wordpress. When he goes to submit, I would like him to add the user in the wp_users table before being logged in because he exists in my external database. Do you have an idea for the interception, or for another way to do it? Thanks in advance for the answers
Thanks @Buttered_Toast ! The answer was to use the wp_authenticate hook and put my custom function as argument. I should have thought about it...
stackexchange-wordpress
{ "answer_score": 1, "question_score": 0, "tags": "plugin development, database, wp login form" }
For each loop on every word in post I'm having a recipe site where every post naturally contains ingredients. Every ingredient is a tag, and I would like to automatically link every ingredient so the user can click on it and see all recipes that uses that certain ingredient. For this to be possible I guess I have to loop through every word in the post, then check if that word is equal to an existing tag, and wrap that word in a hyperlink. But I'm not sure that's the most efficient solution. Do anyone of you have any suggestions here?
Are you sure you want to link every instance of each ingredient? As a user, I wouldn't mind if the ingredient list above the recipe had all its ingredients linked, but if the following instructions continued linking every ingredient I'd find that to be a lot of links I could accidentally tap on and lose the recipe. If you're using the Block Editor, you could use the Tag List block to list the ingredients wherever in the recipe posts you need them. (Optionally you could add a block style to style them differently if you like.) If you're not using the Block Editor, you might want to set up a custom template for recipes, so that the template automatically creates an ingredients section between the recipe title and the rest of the content and outputs the tags there. If you're tagging anything besides ingredients, you could create a custom taxonomy so you're only outputting ingredients and not other unrelated tags.
stackexchange-wordpress
{ "answer_score": 1, "question_score": 0, "tags": "loop, terms, tags" }
PHP File_exist() not working - Checking if File Exist in WordPress Theme Directory I am trying to check if a certain archive file template exists in the WP theme directory. This is my code, I am not sure what I am missing here. <?php $file_name = '/archive.php'; $base_template_dir = get_template_directory_uri(); $file_uri = $base_template_dir.$file_name; $file_uri = str_replace(' '', $file_uri); $file_uri = str_replace(' '', $file_uri); $file_uri = str_replace($_SERVER['HTTP_HOST'], '', $file_uri); if (file_exists($file_uri)) { echo 'File Found: '.$file_uri; } else { echo 'File Not Found: '.$file_uri; } ?>
Most of this code is unnecessary. You're attempting to convert a URL to a path when you could just use the function that returns a path. $path = get_theme_file_path( 'archive.php' ); if ( file_exists( $path ) ) { echo 'File Found: '. $path; } else { echo 'File Not Found: '. $path; }
stackexchange-wordpress
{ "answer_score": 1, "question_score": 0, "tags": "plugin development, theme development, wp filesystem" }
Setting Parent Page to Post Does anyone know how to achieve different parent pages for posts? I've managed to code a Custom Post Type that sits under a specific parent page, but I want the option to change this from post to post. Example; * `/page-1/custom-post-1/` * `/page-1/custom-post-2/` * `/page-2/custom-post-3/` * `/page-2/custom-post-4/` The final result would be URL structure like the above, but all posts sitting on one archive page. I know by default this isn't possible as posts are non-hierarchical. Thanks
This should be in a comment, but can't format much in there. 1. Create a relationship between your CPT and Page. For example, create a custom taxonomy for your CPT and programatically add the pages as terms. Or, you can even create a meta field. 2. Create a placeholder for the URL while registering the CPT. For example `'rewrite' => array( 'slug' => '%cpttag%'),`. 3. `str_replace` the placeholder with page slug you get from term/meta using `post_type_link`. 4. Flush the permalinks (Just hitting Save on Permalinks Settings page will do it)
stackexchange-wordpress
{ "answer_score": 1, "question_score": 0, "tags": "custom post types, customization, url rewriting, seo" }
ACF to select posts not displaying on blog page I am trying to implement a repeater / post object so I can select posts that I want to displaying on the sidebar. I am using this code: <?php while ( have_rows('top_posts_repeater')) : the_row(); // loop through the repeater fields ?> <?php // set up post object $post_object = get_sub_field('selection'); if( $post_object ) : $post = $post_object; setup_postdata($post); ?> <article class="your-post"> <?php the_title(); ?> <?php the_post_thumbnail(); ?> <?php // whatever post stuff you want goes here ?> </article> <?php wp_reset_postdata(); // IMPORTANT - reset the $post object so the rest of the page works correctly ?> <?php endif; ?> <?php endwhile; ?> The code works if I insert it on any page but it doesn't work if I insert it in the blog page. What am I missing?
a `global $post;` before your loops might do the job
stackexchange-wordpress
{ "answer_score": 1, "question_score": 0, "tags": "posts, loop, advanced custom fields" }
How to see which sites use my installed plugins (wordpress multisite) How can I (easily) determine which of my wordpress sites are using a given plugin, on a Wordpress Multisite install? Let's say I have 1,000 wordpress sites on a Wordpress Multisite install. I have 100 plugins. For each plugin, I want to list all of the sites that are using that plugin. In the GUI, I can only see how this can be done in about 1 million clicks. Is there a query I can run against the DB (and maybe cleanup with bash/awk/etc) that will automatically 1. Get all of the plugins installed 2. For each plugin, list all of the sites that use that plugin (by `site-id` is fine) What's a fast way to determine all of the sites that use each of my installed plugins on Wordpress Multisite?
You can list the sites a plugin has been activated on in the shell using WP CLI: sites=$(wp site list --field=url) for url in $sites; do if wp plugin is-active "YOURPLUGINNAME" --url="${url}" --network; then echo "${url}" fi done It will print out the URL of each site on its own line that has that plugin activated.
stackexchange-wordpress
{ "answer_score": 1, "question_score": 0, "tags": "plugins, multisite, admin, maintenance" }
date_query empty results with custom post type I am trying to use `get_posts` to return data between certain dates but I always get an empty result even though there is a lot of data. This is for a custom post type. $args = array( 'post_type' => 'bookings', 'fields' => 'ids', 'post_status' => 'any', 'posts_per_page' => -1, 'date_query' => array( array( 'after' => '2022-01-01', 'before' => '2022-06-01', 'inclusive' => true, ), ) ); $data = get_posts($args); die(var_dump($data)); I also tried something like the below to get a specific date but still an empty array: 'date_query' => array( array( 'year' => 2022, 'month' => 01, 'day' => 21, ), )
Assuming that you're trying to get all posts in the first half of 2022, as opposed to the first 6 days of 2022, then you need to be clearer with your before and after dates. `date_query` uses `strtotime` behind the scenes, which will interpret your dates as Jan 1 to Jan 6. You need to either change the dates to the American format of YYYY-DD-MM, or be more specific by using arrays to express your dates instead.
stackexchange-wordpress
{ "answer_score": 0, "question_score": 0, "tags": "custom post types, wp query, get posts, date query" }
Cannot get wpdb data (Error in a simple fuction) I'm using Cryto Plugin and want to get coin price data from plugin db. ![enter image description here]( For easy practice, I'm trying to get BTC data. <?php function get_coin_price($coin_symbol) { global $wpdb; $coin_price = $wpdb->get_var($wpdb->prepare("SELECT price FROM {$wpdb->prefix}cmc_coins_v2 WHERE symbol = '%s'", $coin_symbol)); return $coin_price; }?> And if I want to get BTC price, I use this code. <?php get_coin_price(BTC); ?> However I'm getting this error **" Use of undefined constant BTC - assumed 'BTC' (this will throw an Error in a future version of PHP)"** Is there a problem in data type? or maybe am I not using $wpdb->get_var or wpdb->prepare correctly?
What about changing BTC to a string `<?php get_coin_price('BTC'); ?>`
stackexchange-wordpress
{ "answer_score": 1, "question_score": 0, "tags": "plugins, functions, mysql, wpdb" }
Can inactive WordPress plugins still load scripts? I recently deleted a contact form plugin (HubSpot All-In-One Marketing) on a site and the contact forms stopped working. Curiously, **the forms work when the plugin is installed and INACTIVE** , but they **do NOT work when the inactive plugin is DELETED**. This means that the plugin being present is affecting the site even when it is inactive. How is this possible? How can a contact form work when a plugin is present and inactive, but not when the plugin is deleted? Can an _inactive_ plugin load script files? Note: The full form code snippets are being included in the page (not shortcodes or anything else referring to the plugin).
Many hypotheses could be made, but the most probable ones are that the theme or a third plugin loads the script if a specific option saved in the database has a certain value. If the plugin is installed but not active that hypothetical option still exists in the database, on the contrary, when you delete the plugin, it will delete that option. Another hypothesis is that you think the plugin is deactivated, but a third plugin filters the option "active_plugins" in a mu-plugin, and on the frontend that plugin is active, even if in the page of plugins you see it disabled. Another hypothesis is the script is loaded by a caching plugin, and it was a coincidence that when you deleted the plugin the cache was also deleted. You can do also other suppositions, but without having more details you can only guess.
stackexchange-wordpress
{ "answer_score": 1, "question_score": 0, "tags": "plugins, scripts" }
Add leading zero to current post display I am using the next to show in a loop of posts the current post and the total of posts published. $post_query = new WP_Query($args); $postAmount = wp_count_posts( 'post' )->publish; <?php echo $post_query->current_post + 1 ?> / <?php echo $postAmount ?> This returns 1/20, 2/20, etc Does someone know how to add a leading zero so it shows 01/20, 02/20, etc? Thanks a lot in advance
should work with `sprintf('%02d', $post_query->current_post + 1) `
stackexchange-wordpress
{ "answer_score": 2, "question_score": 0, "tags": "loop" }
custom tables in wordpress Database? (can i just create them with sql?) i just want to create a custom Table in my WordPress database and i saw many php functions to deal with that my question now is : can i just create them with an sql command and for what do i need to keep an eye on ?
Yes, you can. WPDB Class is quite beneficial in manipulating the database.
stackexchange-wordpress
{ "answer_score": 0, "question_score": 0, "tags": "database, sql" }
save_post_{CPT} not updating the 'sticky_posts' option add_action( "save_post_{CPT}", 'update_sticky', 15, 1 ); function update_sticky( $post_id ) { $stickies = get_option( 'sticky_posts' ); if ( ! in_array( $post_id, $stickies ) ) { $stickies[] = $post_id; update_option( 'test', $stickies); update_option( 'sticky_posts', $stickies ); } } * It **does** work for `test` option I created for testing, but **it doesn't** work for existing `sticky_posts` option, although everything is the same. * It does work for both if I hardcode the $post_id, like: `$stickies[] = 123;` * Tried it in `functions.php` file, as well as in the class in which I am registering the CPT, same results - `test` is working, while `sticky_posts` is not. * Tried different action priorities, 5, 10, 15, 99 Any ideas?
Most likely what you're are experiencing is that within the `edit_post()` the updated post is automatically removed from the sticky posts. This happens for users that can publish posts and edit others post's, after the post is updated and the `save_post` hooks have fired. Note that core uses helper functions like `stick_post()`, `unstick_post()` and `is_sticky()` to do this kind of task. As far as I understand the sticky posts feature is only fully implemented for the the built-in post type. So I'm not sure it's a good idea to mix it with other custom post types.
stackexchange-wordpress
{ "answer_score": 1, "question_score": 1, "tags": "options, save post, sticky post" }
How do I add a tag slug to a category URL to filter posts? I want to add an option to my site to filter posts by one specific tag on the category page and at the same time have a nice URL (no query strings). So something like this: ` \- standard category link (currently) ` \- a page like the above, but displaying posts from a specific category AND tag. Is this possible? If so, how can I achieve this? * * * I would also like to note that for posts I have such a slug ` and I'm worried that there might be a conflict with this.
Ok, I found a solution. By default in WP there is an option to filter categories by tags. E.g. ` I added a rewrite rule and redirection: < add_action( 'init', function () { add_rewrite_rule( '([a-z0-9-]+)\/tag\/([a-z0-9-]+)\/?$', 'index.php?category_name=$matches[1]&tag=$matches[2]', 'top' ); } ); < add_action( 'template_redirect', function () { if ( is_category() && is_tag() && ! empty( $_GET['tag'] ) ) { wp_redirect( get_category_link( get_the_category()[0] ) . 'tag/' . get_query_var( 'tag' ) . '/' ); exit(); } } ); Of course it's just such a basic code. It will require additional adjustments, e.g. for SEO.
stackexchange-wordpress
{ "answer_score": 1, "question_score": 0, "tags": "categories, url rewriting, urls, tags, slug" }
Let current user know pending posts counts using wp_query I'm working on a query to let a logged-in user know if the user has more than 5 pending posts. Here's what I ended up with: // Start the query $query = new WP_Query( array( 'post_type' => 'post', 'author' => get_current_user_id(), 'post_status' => 'pending', 'posts_per_page' => -1 )); // Start the loop if ( $query->have_posts() ) { if ( $query->found_posts >= 5 ) { echo '5 or more pending posts'; } else { echo 'Less than 5 pending posts'; } wp_reset_postdata(); } else { echo 'Nothing found!'; } It seems working. Is there anything missing? Is there anything to correct?
As others have already noted in the comments, using `"posts_per_page" => 5,` is better option than `"posts_per_page" => -1,` for your query as it will give you the information you need for your conditional check. Limiting what is queried is also something to consider - as honk31 mentioned. Along `'fields' => 'ids'` you can also add the following lines to your query. * `'no_found_rows' => true` \- number of total rows not needed in this case * `'update_post_meta_cache' => false` \- meta not needed in this case * `'update_post_term_cache' => false` \- terms not needed in this case The `$query->have_posts()` with `wp_reset_postdata();` is also a bit unnecessary as you can just use `$query->found_posts` or `->post_count` directly. if ( $query->found_posts ) { echo $query->found_posts >= 5 ? '5 or more pending posts' : 'Less than 5 pending posts'; } else { echo 'Nothing found!'; }
stackexchange-wordpress
{ "answer_score": 0, "question_score": 0, "tags": "php, functions, wp query" }
comments_where Hook Is there a similar replacement of the hook posts_where for comments (`WP_Comment_Query`)? I need to modify the where clause for a comments query like it is shown in this tutorial (“4. Sub custom field values”) for posts. The only hook I found is comments_pre_query, but the property `$query->meta_query_clauses[ 'where' ]` is protected.
Yes, a quick search of developer.wordpress.org reveals `comment_feed_where`. Note that this won't work with `get_posts` unless suppress filters is turned off, and that what you're trying to do is going to be very slow with some unreliability. There is also `comment_clauses`: <
stackexchange-wordpress
{ "answer_score": 0, "question_score": 0, "tags": "custom field, comments, advanced custom fields, comment meta, wp comment query" }
How to add $args to any running wp_query from function.php? Is it possible to add WP_Query arguments from functions.php to any of wp_query running on current page? For example, I want to add $args['order'] to current running wp_query on any pages.
Use a `pre_get_posts` hook to modify the relevant query variables, with conditional tags to target specific pages/queries (and probably return from the callback early on `is_admin()` so you do not affect dashboard queries).
stackexchange-wordpress
{ "answer_score": 1, "question_score": 0, "tags": "wp query" }
how do I turn off whatever causes links to be embedded as URL's site title When I print a url onto my site, it automatically gets wrapped in: <blockquote class="wp-embedded-content" data-secret="tDj3qpdVAi"><a href=" Domain</a></blockquote> even though all I printed to the page is " What is this mechanism and how can I disable either on a specific page or site-wide? **What I Tried** * adding the code here to my functions file: < * adding both snippets of code (separately) from here to my functions file:
Print that plain text url as a link: <a href=“
stackexchange-wordpress
{ "answer_score": 0, "question_score": 0, "tags": "links, embed" }
Can you disable typography panels for just the paragraph block? I'm wondering if there is a way to remove the typography and custom color panels from the sidebar for _just_ the paragraph block. I've currently written a function that I've added add_theme_support to for the typography panel and custom color picker but it's affecting every block that can utilize those things. Here is said function: public function typography_custom_color_theme_support() { // Disable Custom Color Picker add_theme_support( 'editor-color-palette' ); add_theme_support( 'disable-custom-colors' ); // Disable Font Size and Custom Font Size Dropdowns add_theme_support( 'editor-font-sizes' ); add_theme_support( 'disable-custom-font-sizes' ); } If possible, could I add a conditional to this along the lines of "if paragraph block is selected run add_theme_support actions?" Thank you.
yes you can remove those options via theme.json but it has to be done block by block. This might help you (not my course): <
stackexchange-wordpress
{ "answer_score": 1, "question_score": 1, "tags": "block editor" }
Count posts per taxonomy else change taxonomy if less than x number $taxonomy = $tag->count > 3 ? 'post_tag' : 'category'; $cats_or_tags = $tag->count > 3 ? $tag_ids : $cat_ids; $args = array( 'tax_query' => array( array( 'taxonomy' => $taxonomy, 'field' => 'id', 'terms' => $cats_or_tags The first part of this ternary works when checking the count of posts in a specific tag but the 2nd part doesn't. It's supposed to set the taxonomy and terms values if there's more than 3 posts tagged otherwise when less than 4, display posts from categories instead of tags.
I'm guessing you are using a `tax_query` here. If you try to query multiple categories or taxonomies, the terms field expects an `array` $args = array( // other query arguments 'tax_query' => array( array( 'taxonomy' => $taxonomy, 'field' => 'id', 'terms' => array($cats_or_tags), ), ), );
stackexchange-wordpress
{ "answer_score": 1, "question_score": 0, "tags": "wp query, terms" }
I don't think WordPress is loading jquery or bootstrap js I'm building a WordPress theme and I've used the code from < to build my slider I've also used < I have both jquery and bootstrap both linked to the site they appear in inspect element however they do not seem to be running as my drop down navigation does not work on mobile size and the slider doesn't slide ![enter image description here]( function wpbootstrap_enqueue_styles() { wp_enqueue_style( 'bootstrap', get_template_directory_uri() . '/css/bootstrap.css' ); wp_enqueue_style( 'my-style', get_template_directory_uri() . '/css/style.css'); wp_enqueue_script('bootstrap-js', get_template_directory_uri() . '/js/bootstrap.js', array('jquery'), NULL, true); wp_enqueue_script('jquery-js', get_template_directory_uri() . '/js/jquery.js', array('jquery'), NULL, true); } add_action('wp_enqueue_scripts', 'wpbootstrap_enqueue_styles');
WordPress is loading jQuery as default. You basicly telling WordPress to load your `jquery-js` after the `jquery` script from WordPress. The Nav_Walker class you are using is related to Bootstrap Version 3. Which Version of Bootstrap are you loading? Without knowing your code, I think I'm guessing that the Boostrap version does not cope with the current markup.
stackexchange-wordpress
{ "answer_score": 0, "question_score": 0, "tags": "theme development, jquery, twitter bootstrap" }
Where Do I Find The Astra Default Font Family That All Text Elements Are Inheriting From? I'm working with the Astra theme and I'm looking at my Typography settings in the Customizer. All of the elements (body, H1, H2, etc) have the Font Family set to Inherit. Where do I find the actual font family that these are all inheriting from, in case I want to change this? LMK if you need more information.
By default, Astra uses 'system fonts'. To change the defaults, look in Appearance / Customize / Global. < Best of luck!
stackexchange-wordpress
{ "answer_score": 0, "question_score": 1, "tags": "css, fonts" }
Serialize data before inserting into the DB I need to store some post IDs in the DB in a custom table/field. The IDs will have to be stored in a serialized format. I know that, ie. for the options, serialization is done automatically for add/update functions (`add_option()`, `update_option()`). Is there a built-in WP function to serialize data for any other case? Or should I just use `serialize()`? Similarly, as soon as the data will be retrieved, is there a stock WP function to unserialize it, or will I have to use `unserialize()`? Thanks in advance for your replies!
WP functions... Serialize: maybe_serialze Unserialize: maybe_unserialize
stackexchange-wordpress
{ "answer_score": 1, "question_score": 0, "tags": "database" }
Format meta_value I have a request to get postmeta records with a specific meta_value. global $wpdb; $result = $wpdb->get_results ( " SELECT * FROM $wpdb->postmeta WHERE $wpdb->postmeta.meta_key LIKE 'wpcomplete' " ); foreach ( $result as $page ) { echo maybe_unserialize($page->meta_value).'<br/>'; } result : {"buttons":{"3":"1951965-debutant","4":"1951965-intermediaire","5":"1951965-expert"},"course":"examen"} I just need to clean the result like that **buttons :** 1951965-debutant 1951965-intermediaire 1951965-expert **course :** examen
It seems the meta value is _double_ serialized. Try this, it also cleans up your query, untested: $results = $wpdb->get_column ( " SELECT meta_value FROM $wpdb->postmeta WHERE meta_key LIKE 'wpcomplete' " ); foreach ( $results as $result ) { $item = maybe_unserialize( $result ); if ( is_serialized( $item ) { $item = maybe_unserialize( $item ); } foreach( $item as $obj ) { foreach( $obj->buttons as $key => $value ) { echo $value . '<br>'; } foreach( $obj->course as $key => $value ) { echo $value . '<br>'; } } } If you know that the meta_key is exactly `'wpcomplete'`, then do not use `LIKE` \- it is slow. Instead, do this: `WHERE meta_key = 'wpcomplete'`
stackexchange-wordpress
{ "answer_score": 0, "question_score": 0, "tags": "post meta" }
Retrieve user roles but exclude default roles I am currently using the **wp_roles()** function to retrieve all user roles available like this: <?php foreach (wp_roles()->get_names() as $role) { echo translate_user_role( $role ); } ?> How would I retrieve an array/list of all _custom roles_ that I've created without the default roles (Administrator, Editor, Subscriber, etc) included?
So I ended up using a combination of the array_filter function and the in_array function to retrieve all custom roles like this: <?php function check_roles($userRole) { $default_roles = array('Administrator', 'Editor', 'Author', 'Contributor', 'Subscriber'); if (!in_array($userRole, $default_roles)) { return $userRole; } } $all_roles = wp_roles()->get_names(); $custom_roles = array_filter($all_roles, 'check_roles'); foreach ($custom_roles as $role) { echo $role; } ?>
stackexchange-wordpress
{ "answer_score": 0, "question_score": 0, "tags": "user roles" }
Update current WP post every 3 minutes I wish to auto update/publish the changes of a post I am editing every 3 minutes. Any idea how can I achieve that?
**Classic Editor:** autosave.js file setInterval(function () {document.getElementById("publish").click()}, 300000); php function // Load js file on specific post type in class editor function load_js_file_classic_editor( $hook ) { global $post; if ( $hook == 'post-new.php' || $hook == 'post.php' ) { if ( 'post' === $post->post_type ) { wp_enqueue_script( 'myautosave', get_stylesheet_directory_uri().'/includes/js/autosave.js' ); } } } add_action( 'admin_enqueue_scripts', 'load_js_file_classic_editor', 10, 1 ); **Gutenberg** setInterval(function() { wp.data.dispatch( 'core/editor' ).savePost(); }, 60 * 1000); // 60 * 1000 milsec
stackexchange-wordpress
{ "answer_score": 1, "question_score": 0, "tags": "save post" }
Bulk-add featured images in posts with no featured image I have a site with loads of posts (news items). Some posts don't have featured images yet. Adding the images to those posts (few hundreds) is a tedious task. We basically want to add 1 and the same image to all the posts without a featured image. Is there a way to do this in bulk? Like ADD 'this image' to ALL 'posts' (not pages) WHERE 'featured_image' is empty. I really hope there's a plugin for that. Can't find it though.
you can use this plugins as you like : < <
stackexchange-wordpress
{ "answer_score": 2, "question_score": 0, "tags": "images, post thumbnails, bulk" }
Should I include colon in my msgid in PO file? Which of the below is recommended when creating msgid a PO file? msgid "Available Balance:" or msgid "Available Balance"
The use of each depends on your choice. If, for example, the text is in front of a field, I think it is better to use the symbol: In general, you should see if it really needs it or not. You do not have to use it or not. In the text you sent, the first option is more appropriate because the intention is to display a value in front of or below this text
stackexchange-wordpress
{ "answer_score": 1, "question_score": 1, "tags": "translation, localization, plugin wpml, plugin qtranslate, plugin polylang" }
setcookie on WordPress Page Template I am having an issue with setcookie. I need to set a cookie on a page action (form). I have tried on the template file, but not working. then find out if I set it from functions.php with init hook, it's working. then I put condition like if(is_page_template('mytemplate.php')){... then it's not working. how can I do that? here is my code. add_action( 'init', 'hello_my_cookie' ); function hello_my_cookie() { if(is_page_template('mytemplate.php')){ if(isset($_POST['GGmyCookie'])){ setcookie( 'myCookie','Hello Cookie!', time()+3600); } } }
This fails because the `init` hook is far too early to call `is_page_template`. Conditionals such as this function use the main query to decide their value, but WordPress hasn't created the main query yet. The earliest hook you can safely do this is `template_redirect`.
stackexchange-wordpress
{ "answer_score": 0, "question_score": 0, "tags": "themes, cookies" }
How to replace username with email address in users table I have a custom built site that does not use usernames and everything requires use of their email address. The username is auto generated and looks bad in the table. I know there are filters and actions to work with custom columns within the users table but I have been looking for a way to replace the username with the email address. I know I can unset the username using `manage_users_columns` filter but I then loose the row actions. Is there a way to accomplish this without rewriting wordpress core functions? Edit - Clarification: I am looking to replace the username column in the users.php table.
It seems that the `username column content` is hardcoded in `single_row()` of `WP_Users_List_Table` and there isn't a filter you can use to change it. A hacky way is to enqueue some javascript on the users view and have the script change the content. Or take the rocky road by duplicating the code that handles the row actions in `single_row()`, and replace the default column with a custom one showing the email and the actions. Or just brute force the email as the username with `wp_pre_insert_user_data` filter.
stackexchange-wordpress
{ "answer_score": 1, "question_score": 0, "tags": "filters, wp admin, users" }
How to get authors who have added the post in the specific custom post type I have a custom post called `event` and I have to show all the authors who have added the post. I have tried the below code but I am getting all the users on the page. For example. There are 4 users called A, B, C, and D on the website and A and B added the post. Now I have to get only A and B users but below code getting all the users like A,B,C,D Any idea how to get the user to add the post in the event post type. $users = get_users( array( 'fields' => array( 'ID','display_name' ),'order' => 'ASC', 'who' =>'authors' )); foreach ($users as $user){ $userid=$user->ID; //echo $post_count = count_user_posts($userid); echo '<li><a href="'.esc_url(get_author_posts_url($userid)).'">'.$user->display_name.'</a></li>'; }
When you say "who have added the post", are you meaning all users who have written at least 1 post of the event post type? If so, you can get all the authors of all events like so: $event_posts = get_posts([ 'post_type' => 'event', // Or whatever your event post type is 'numberposts' => -1, ]); // Get all the author (user) IDs of all events $event_author_ids = wp_list_pluck( $event_posts, 'post_author' ); // Now get all the user objects $users = get_users([ 'include' => $event_author_ids, ]); Alternatively, if you are meaning the author of the _current_ event post, there can only ever be one author per-post, and you can just use the author template tags whilst in the loop. echo get_the_author_link(); // Get author <a /> HTML echo get_the_author_meta( $prop ); // Get author property e.g. display_name, user_email, first_name etc.
stackexchange-wordpress
{ "answer_score": 0, "question_score": 0, "tags": "plugins, theme development, list authors" }
How to Get Posts, Including Private Ones? Currently in one of my php files, I retrieve all of the public posts like this: $posts = get_posts(array( 'posts_per_page' => -1, 'post_type' => 'post' )); However, this only returns _public_ posts, and I would like to store all posts, both public and private, in the `$posts` variable. How can I accomplish this?
Set the `post_status` argument to an array of desired post status strings, or to the string `any` to query regardless of status entirely: $posts = get_posts(array( 'posts_per_page' => -1, 'post_type' => 'post', 'post_status' => array( 'publish', 'private' ), ));
stackexchange-wordpress
{ "answer_score": 3, "question_score": 0, "tags": "posts, get posts" }
Do I have to use load_plugin_textdomain() or is there any default folder for languages? When I develop a plugin, do I always have to use: load_plugin_textdomain('whatever', '', 'whatever/languages'); Or is there any setup, so that I put my translations into a specific folder with a specific name and they get loaded by default with the domain being the plugin slug? Reason is, I don't like to use that second deprecated paramenter. I prefer to omit the whole call to the function if a default setup exists.
Yes but it is not useful if you plan to bundle your language files with your plugin: < > If the path is not given then it will be the root of the plugin directory. So it will look in `wp-content/plugins` The third parameter is only used if you want to use a subfolder. Likewise, if a file exists at `wp-content/languages/plugins/` that matches your text domain and locale then it will be loaded. * * * **Although, you can just pass`false` as the second parameter, the only reason it's throwing deprecation warnings is because you've passed `''`.** So pass `false` for the second parameter, and use the 3rd parameter. The two parameters behave differently so changing the second parameters behaviour would have been a break in backwards compatibility. So a 3rd parameter was added and the second was deprecated. This doesn't mean you need to avoid the function, just pass `false` **( passing`false` is not deprecated )**.
stackexchange-wordpress
{ "answer_score": 1, "question_score": 0, "tags": "localization" }
Display if author page is author page of current user in my multi author website I have a button that users can upload their avatars. I need to display this button in author page. I can do it. I added this button to author page. The problem is that author can see this button in other author's page too . That's why I need to display this button in author page of current user. I am so sorry I have no any reference code. I have no any idea how to do it. please help. Thank you for you attention. how to code that if current author page belongs to current user
The `is_author()` conditional can be used to check if the query is targeting an author's page. By passing one or more User IDs/nicenames into it, it will check for specific author pages. So to check if the current author page is for the current user, it can be passed the return value from `get_current_user_id()`: if ( is_user_logged_in() && is_author( get_current_user_id() ) ){ echo "belongs to current user "; } else { echo "not belongs to current user"; }
stackexchange-wordpress
{ "answer_score": 1, "question_score": 0, "tags": "wp query, users, archives, author, session" }
Replace post title based on conditions So I would like to replace the entire title of posts in WordPress bases on user behaviuor and role. Please note that I would like to replace the entire post title and not the prepend or append text to it. Each post has a 'default' title, which is the title of the post, like "Make No.1245/12.02.2022 on model 2376/2021". The alternative title would be "Make No.*******/********.2022 on model *******/2021" basically replacing certain parts of the title with asterisks, essentially hiding it. If the user is logged in AND has role 'subscriber' THEN he/she sees the default post title. If the user is visitor (not logged in) OR is logged in but his role is 'pending' THEN he sees the alternative post title.
You can use `the_title` filter to modify the post_title prior to printing on the screen. add_filter("the_title", function($title, $id)){ $user = wp_get_current_user(); if((!is_user_logged_in() || in_array("pending", $user->roles)) && "post" === get_post_type($id)){ $title = "Custom title"; } return $title; }, 10, 2); source: <
stackexchange-wordpress
{ "answer_score": 0, "question_score": 0, "tags": "get the title" }
Alias to theme folder for local development I am locally developing a parent theme and child themes simultaneously (perhaps not best practice, but...). It looks something like this: parent.local /wp-content/themes/parent-theme/ child1.local /wp-content/themes/parent-theme/ /wp-content/themes/child1-theme/ child2.local /wp-content/themes/parent-theme/ /wp-content/themes/child2-theme/ Rather than copying the parent theme to each local site, I want to be able to work on the parent theme in one place and keep it updated for the child sites as well. I have tried creating an alias (on Mac) to the parent theme folder under each child site, but Wordpress says the parent theme is not installed. Is there another way to do this? I feel like I'm missing something obvious, but any help is appreciated.
Got it—needed to use a symlink rather than an alias. cd ~/child1.local/wp-content/themes/ ln -s ~/parent.local/wp-content/themes/parent/ parent Figured it out with help from this article.
stackexchange-wordpress
{ "answer_score": 1, "question_score": 1, "tags": "theme development, child theme, local installation" }
Disable gzip on WordPress I can see WordPress enables Gzip compression on the site I disabled all plugins to ensure that no plugin enabled that And also I created a simple php script and it doesn't enable gzip by default by Web Server So I think WordPress enable Gzip in it's code How can I prevent WordPress to enable Gzip?
1. Check `.htaccess` on `/home/` and `/homr/public_html/` (For example of site root), Probably there are some codes there to add gzip to the web server 2. a web server can enable the gzip as default 3. check `php.ini` file for `zlib.output_compression` value, It should be off
stackexchange-wordpress
{ "answer_score": 0, "question_score": 0, "tags": "compression" }
How do a I add an attribute to <html> element (when using block theme)? I have a WordPress website that is using the Twenty Twenty-Two block theme (more specifically, a child theme of it). I want to edit the `<html>` root HTML element to add an attribute. I want this line of code: <html lang="en-US"> ... to change into this line of code: <html lang="en-US" foo="bar"> Since this a block theme, there is no `header.php` file to edit. How do I do this?
It's possible to use the language_attributes filter as before since the template canvas in FSE contains: <html <?php language_attributes(); ?>> Add this code to the appropriate place in your theme or plugin: <?php add_filter( 'language_attributes', function($lang_attributes) { return "$lang_attributes foo=\"bar\""; });
stackexchange-wordpress
{ "answer_score": 2, "question_score": 1, "tags": "block editor, html" }
Create page (not the post type) dynamically I'm working on a custom plugin where the user/customer will be purchasing a ticket (it'll be a woo product) to take a quiz and win some prize... So suppose the URL of a product/quiz would be like `mydomain.tld/product/play-and-win-samsung-galaxy-s22` When the user purchases a ticket to participate in the quiz, I want to redirect them to a page like `mydomain.tld/product/play-and-win-samsung-galaxy-s22/play` where they will actually take the quiz. Needless to say that in that page the necessary checks will be taking place (like whether the user is logged in and has purchased a ticket)... So how can I create such a dynamic page (not a PT Page), that's dynamic? By dynamic I mean, it'll be 100% programmatically created. No shortcodes attached to a PT Page, nothing. Just pure code... How do we start such a task? Thank you for any suggestions.
You need to register a 'rewrite endpoint' using `add_rewrite_endpoint()`: <?php add_action( 'init', function() { add_rewrite_endpoint( 'play', EP_PERMALINK ); } ); Now, after flushing permalinks, in whatever template or code you're using for your products you can check this to determine whether the `/play` version of the URL is being accessed: <?php if ( false !== get_query_var( 'play', false ) ) { // True for mydomain.tld/product/play-and-win-samsung-galaxy-s22/play } else { // True for mydomain.tld/product/play-and-win-samsung-galaxy-s22 }
stackexchange-wordpress
{ "answer_score": 1, "question_score": 0, "tags": "plugin development, pages, url rewriting, page template" }
Get single item from cURL plugin API call inside bash I'm trying to get only the `last_updated` date from a plugin through an API call in a bash script. I'm trying to use cURL but that's giving me some issues. On the browser I can get to to plugin like this: [ Looked over here but this seems more geared towards PHP: < <
Since it seems the API is closed source and there may not be a way to get only a single option then the only other option is parsing the response. I hear jq is the way to go for parsing JSON within the shell, but I don't want to add dependencies and grep seems to have done the job: `curl -v -d 'action=plugin_information&request[slug]=custom-comment-links' --stderr - | grep -o '"last_updated":"[^"]*' | grep -o '[^"]*$'` You can replace `last_updated` with anything you'd like :)
stackexchange-wordpress
{ "answer_score": 1, "question_score": 0, "tags": "wp api, curl" }
How to safely escape data that contains HTML attributes I am not looking for esc_attr(), which escapes data to be used within attributes. I am looking for a function that outputs one or more HTML attributes within an HTML tag. For example: <div <?php echo escape_me('class="whatever"'); ?> >hey</div> What should I use?
### wp_kses You could use `wp_kses` to define specific html-tag/attribute combinations to be permitted in the escaped output. $allowed_html = [ 'div' => [ 'class' => [], ], ]; echo wp_kses( '<div class="whatever">hey</div>', $allowed_html ); ### wp_kses_post You could use `wp_kses_post`. It's a pretty heavy function to use for such a purpose, but it is a valid way to escape your output. <div <?php echo wp_kses_post('class="whatever"'); ?> >hey</div>
stackexchange-wordpress
{ "answer_score": 1, "question_score": 1, "tags": "escaping" }
Where are the layout defaults in Twenty Twenty Two coming from? When I'm editing the template for a Single Post using the Twenty Twenty Two theme, there's a layout option for the post content block that says it will inherit the default layout. Where is that default coming from? Is that a site-wide default or a theme default? Here's a screenshot that shows what I'm talking about: ![enter image description here](
> there's a layout option for the post content block that says it will inherit the default layout. Where is that default coming from? In block themes, the default layout settings (`contentSize` and `wideSize`) can be found in the `theme.json` file in the root theme folder, e.g. at `wp-content/themes/twentytwentytwo/theme.json` in Twenty Twenty-Two. See source on GitHub for WordPress v5.9.3 & Twenty Twenty-Two v1.1 And if the `layout` option does not exist in the `theme.json` file, i.e. `settings.layout` is not defined, then the "Layout" panel (in the Block Settings sidebar) _will not include_ the toggle labeled "Inherit default layout".
stackexchange-wordpress
{ "answer_score": 4, "question_score": 2, "tags": "block editor, theme twenty twenty two" }
How to conditionally add Custom Post Type to Front Page I am using the following code to show my custom post types on my front page along with the default post type: // allows the products to show up on the main page function add_custom_post_type_to_query( $query ) { if ( ! is_admin() && $query->is_main_query() ) { if ( $query->is_date() || $query->is_home() ) { $query->set( 'post_type', array('post', 'product') ); } } } add_action( 'pre_get_posts', 'add_custom_post_type_to_query' ); How would I modify this code to only show/add custom post types of `product` where the custom field called `show_on_front_page ` which is a boolean (ACF checkbox) is set to true (checked)?
I believe that if all your products have the custom meta field `show_on_front_page` with some containing `'1'` and some containing `'0'` or some such, AND your regular posts do not have that field, then something like below should work: //... $query->set('post_type', array('post', 'product')); //add this $meta_key = 'show_on_front_page'; $query->set('meta_query', array( 'relation' => 'OR', array( 'key' => $meta_key, 'value' => '1', 'compare' => '=' ), array( 'key' => $meta_key, 'compare' => 'NOT EXISTS' ) ) ); //... Caveat: If some of the products don't have the meta field set to anything they will show as well. See <
stackexchange-wordpress
{ "answer_score": 1, "question_score": 0, "tags": "custom post types, custom field, loop, query, frontpage" }
how to test if an open graph image has been set Our content mostly has Open Graph information set. I think this is done by Yoast SEO. Do you think this is correct? There are quite a few (~1200) URLs that have no Open Graph image set. I am thinking I can write a `functions.php` action to check to see if the Open Graph image has been set, and if not, supply a fallback OG image. How would I check to see if an OG image has not been set? Help appreciated.
Yoast SEO has a provision for a default social image through `Yoast SEO > Social > Facebook > Default image`.
stackexchange-wordpress
{ "answer_score": 0, "question_score": 0, "tags": "open graph" }
Delete a repeated part of post title in WordPress All of my posts have the words (With Table) at the end of post title. I want to delete this part in every post title but can't do it manually because there are 10,000+ posts I tried Better Search Replace plugin but it tells me I have 21,000 matches whereas I only have 12275 posts in my WordPress (there are no draft, pending or trash posts) Is there any easy way to do this bulk change by using some code or plugin? I will take backup before trying a solution.
if you have access to your database, as every posts are registered in the (wp_/ or whatever is your prefix )posts , you can probably do it via sql something like update wp_posts SET post_title = substring(post_title,1, CHAR_LENGTH(post_title) - 10)) WHERE post_title like '%With Table'
stackexchange-wordpress
{ "answer_score": 1, "question_score": 0, "tags": "title" }
How Can i import plugin option? hey guys i'm trying to import my plugin option into wordpress with php but i can't find any tutorial or describe about this section i have this example: my option name: > get_option('meow'); what i have in this option are 'cats'=> '2', 'food' => array('tona','fish'), so how can i use > update_option to import this values? i tried this way but it's not working update_option('meow', 'cats','5');
Just pass the array as the second argument to `update_option` \- WordPress will serialize the value before storing it in the database, and automatically unserialize it when you read it: update_option( 'meow', array( 'cats' => '2', 'food' => array( 'tona', 'fish' ), ) ); $meow = get_option( 'meow' ); print_r( $meow ); // Array // ( // [cats] => 2 // [food] => Array // ( // [0] => tona // [1] => fish // ) // )
stackexchange-wordpress
{ "answer_score": 0, "question_score": 0, "tags": "plugins, plugin development" }
Remove Body Classes I need to remove specific body classes added as a comma separated delimited list to a custom field input field like this wp-custom-logo, single-post, postid-28, single-format-standard, logged-in, admin-bar Using this code only allows me to remove 1 class add_filter('body_class', function (array $classes) { if ( ! is_singular(array( 'post', 'page' ) ) ) { return; } $body_classes = get_post_meta( get_the_ID(), '_remove_body_classes', true ); unset( $classes[array_search($body_classes, $classes)] ); return $classes; }); This code works when trying to remove 1 class on single posts but doesn't work when using a comma delimited list and also doesn't work on single pages.
One (untested) suggestion is to replace: unset( $classes[array_search($body_classes, $classes)] ); with $classes = array_diff( $classes, wp_parse_slug_list( $body_classes ) ); assuming the classes survive `sanitize_title` from `wp_parse_slug_list()`. It should also be alright with empty arrays. We also note that `wp_parse_slug_list()` is using `wp_parse_list()` to parse the comma separated string.
stackexchange-wordpress
{ "answer_score": 1, "question_score": 1, "tags": "custom field, array, body class" }
get value from 'terms' table so I feel like I am missing something very obvious, but I need to get a value from the database table 'terms', and it seems get_terms fetches from taxonomy table. I've tried get_term_by as well but to no avail. I could simply build a regular request and get the data needed, no worries. But I feel like I must be missing something obvious, as it has to be a regular occurance among wordpress users to fetch data from that table. /Regards Sonny
`get_terms` does indeed fetch from the terms table, but it does also use a join on the taxonomy table, since you need to specify which taxonomies you want terms for in your `get_terms` query. If you want to get _all_ terms, you could use something like: $all_terms = get_terms([ 'taxonomy' => get_taxonomies(), 'hide_empty' => false, ]);
stackexchange-wordpress
{ "answer_score": 0, "question_score": 0, "tags": "database, terms" }
How to change wordpress RSS to be in a specific format? I am working with an old system that takes in very specific format for RSS. The one thing that doesn't work is the featured image. I need the image to be in a <image> <url></url> </image> form but on Wordpress the image always shows in . Any help here please? Thanks!
You can use the action `rss2_item` (and `rss_item` for RSS 0.92) to output the required tags: function wpse_406826_rss_featured_image() { $src = get_the_post_thumbnail_url( null, 'medium' /* or whatever size you need */ ); if ( $src ) { echo "<image><url>$src</url></image>"; } } add_action( 'rss2_item', 'wpse_406826_rss_featured_image' ); add_action( 'rss_item', 'wpse_406826_rss_featured_image' );
stackexchange-wordpress
{ "answer_score": 1, "question_score": 0, "tags": "rss" }
Hook before user is created and make some custom validation I try to hook in user creation process in admin dashboard `/wp/wp-admin/user-new.php` to make some custom validation on data with the following hook, but the hook is not executed on form submit. What goes wrong in this case? What I want, I have a custom ACF relation field which should be mandatory only if the selected role is editor. So I want to parse the request and check against the rules. If it fails than do not create the user return the custom error message. add_action( 'register_post', function($user_login, $user_email, $errors) { var_dump('test'); die; $userIsValid = ValidateUser::make($errors); if(!$userIsValid) { $errors->add( 'bad_email_domain', '<strong>ERROR</strong>: errors' ); } });
You need to add `, 10, 3` after your closure to set the hook priority and (more importantly) the number of accepted arguments \- otherwise `$user_email` and `$errors` will not be passed. add_action( 'register_post', function ( $user_login, $user_email, $errors ) { $userIsValid = ValidateUser::make($errors); if(!$userIsValid) { $errors->add( 'bad_email_domain', '<strong>ERROR</strong>: errors' ); } }, 10, 3 ); **Update** : The `register_post` hook only fires inside `register_new_user()`, which is only used for user registration via the WordPress login page. To handle errors within the admin (i.e. Users > Add New) use the `user_profile_update_errors` hook instead.
stackexchange-wordpress
{ "answer_score": 0, "question_score": 0, "tags": "customization, hooks, user registration, validation" }
How do I get reusable blocks via frontend REST API? I'm using `/wp-json/wp/v2/blocks` to request all blocks on the frontend, but I just get a response of `[]` even though I've made a reusable block in admin. I suspect that what I mean by block and what Wordpress 6 means are different things, but I've not found the REST API documentation helpful in this regard - perhaps I'm too deep for definitions to be provided. **Why I'm doing this** In WP6, there are reusable blocks. These seem ideal to be pulled down via AJAX so that pages can be otherwise statically cached. Perhaps there's a better way to handle FPC hole-punching but I've not found it, and with a JSON REST API this seems ideal.
> How do I get reusable blocks via frontend REST API? We need to be logged in as a user and additionally add the `wp_rest` nonce to the **block** rest endpoint request, either via the `_wpnonce` POST/GET parameter or via the `X-WP-Nonce` header. See e.g. the docs for more information on the authentication. EDIT: As pointed out in comment, to do what questioner is trying to achieve you would need to create a custom endpoint without authentication as the existing block endpoint checks permission of current user.
stackexchange-wordpress
{ "answer_score": 1, "question_score": 1, "tags": "ajax, rest api" }
RSS: fetch_feed caching with different caching delay per feed? I have seen that the filter wp_feed_cache_transient_lifetime can be used to set the cache period for fetch_feed. But this seems to set it globally for all feeds. Is there a way to have a different cache period per feed? This is useful in my case where I have multiple feeds for quite different purposes. some feeds are clearly being refreshed very quickly, while I don't expect others to be updated more than once per month. The issue with these RSS feeds is if they are not cached properly they slow down the page noticeably.
You can use the second parameter passed to the `wp_feed_cache_transient_lifetime` filter which, in the context of `fetch_feed()`, is the URL of the feed: add_filter( 'wp_feed_cache_transient_lifetime', function ( $time, $url ) { if ( $url === ' ) { $time = MONTH_IN_SECONDS; } return $time; }, 10, 2 );
stackexchange-wordpress
{ "answer_score": 1, "question_score": 0, "tags": "cache, rss" }
How to allow slash(/) on page url Suppose, a url of my wordpress website page is domain.com/journal-submission. How to change the url like domain.com/journal/submission. When I rename the permalink, give slash(/) instead of dash(-) it's not changing anything. I just want to change some of my page url keeping the same permalink settings. Now the permalink is set to post-name [
You can set the slug to `submission` then create a parent page named `journal`
stackexchange-wordpress
{ "answer_score": 1, "question_score": 0, "tags": "permalinks" }
WordPress Plugin- How to Insert Html&JS code in specific Page and specific Div I have some Html& js code relating to this dropbox button by WordPress plugin 1- I want to insert the button in a specifc page for example I have sample page and Sec Page I want to specifiy the page **because it's in all the pages** 2- When I install the plugin always appears in the beginning of the website so How to make it in a spcific `div` for example in the page I'll select ![Dropbox button]( I'm using `add_action()` function it works but as I mentioned appears in every page and in the beginning function hook_html() { ?> <script type="text/javascript" src=" id="dropboxjs" data-app-key="XXXXXXX"></script> <div id="dropboxContainer">hellodrooppp</div> ............... } add_action('wp_head', 'hook_html');
As you want to insert the button on only one/few specific pages you can simply create a shortcode[[Reference]]( and insert it on specific page/pages. Your code will be something like: function hook_html(){ //function body } add_shortcode( 'dropbox_button', 'hook_html' ); And then just edit the specific pages and add the shortcode `[dropbox_button]` to them, you can also choose to add this in any section of the page that you want.
stackexchange-wordpress
{ "answer_score": 0, "question_score": 0, "tags": "plugins, plugin development" }
Hide Published text from custom post types column Is it possible to hide the 'Published' word only on custom post types column? as in image and just leave the date and time? ![enter image description here](
WordPress has a filter for that.. function wpse406965_remove_status( $status, $post, $column_name, $mode ) { //Get the post type. Replace YOUR_CPT with your CPT slug. if ( $post->post_type == 'YOUR_CPT' ) { return false; } return $status; } add_filter( 'post_date_column_status', 'wpse406965_remove_status', 10, 4);
stackexchange-wordpress
{ "answer_score": 0, "question_score": 0, "tags": "custom post types, columns" }
custom post type, hide or disable the status line in publish meta box I have been adding a post type to my theme, how do I hide/disable the status line (All of it) as in image ![enter image description here](
WordPress doesn't provide any filter/hook to override the existing HTML in post submit metabox. So, either you remove the entire metabox and add your own (which will be overkill in your case) or just hide it using CSS or remove that element using JS. function wpse406970_remove_publishing_actions() { global $typenow; if ( $typenow == 'YOUR_CPT' ) { ?> <style> .misc-pub-post-status { display: none !important; } </style> <script> jQuery(document).ready(function($){ $('.misc-pub-post-status').remove(); }); </script> <?php } } add_action( 'admin_head', 'wpse406970_remove_publishing_actions', 999 ); I recommend using both approaches as only JS might show a spalsh of the element before removing.
stackexchange-wordpress
{ "answer_score": 1, "question_score": 0, "tags": "custom taxonomy, post status" }
How to insert and call new data in wordpress website database through a plugin I have a dropbox button that user interact with it to get some data like video's id and video's name using Js code. What I want to do is insert these data in the database using `pair` data structure and calling it in when it needed. I found out that I can do this using `add_metadata` or `add_options` which one shoukd i use? and is there better sutiable way. Second thing: I have the button here implemented through `add_shortcode` using a tag but I want to replace the tag with html class in the page because I've to to write the tag like `[]` to add the button. ![The button](
The right place to store the data depends on how you will be using the data. From the context, it sounds like metadata might be the right place. There is `usermeta` if the data relates to one of your site users, or `postmeta` if the data relates to a specific post/page/CPT. Options are best reserved for data that affects the site as a whole. So, if you were going to use the data to populate a video that appears sitewide, `options` would be an appropriate place to store the data. But the `options` table can tend to get bloated and impact site performance, so it's especially inappropriate if the data doesn't relate to the site as a whole, or a large part of the site.
stackexchange-wordpress
{ "answer_score": 3, "question_score": 0, "tags": "plugins, plugin development, database" }
Wordpress Full Site Editing: How can I access my posts listing page? In WordPress 6.0, I've created a block based theme using fullsiteediting.com's theme generator. It had a default homepage which listed posts. Within the block editor (sidebar->Templates->Add New button), I added a "Front Page" for the theme. Now that template is set as the homepage. So, how can I see the list of all posts in the website now? In WordPress Settings->Reading, it's still set to "Your latest posts" as the homepage. Is this some disconnect that the developers haven't cleared yet? Should I create a new page in Pages that will query all the posts?
Yes it sounds like there might be some sort of disconnect, as the template editor doesn't make this clear, but keep in mind that FSE is still marked as being in Beta in the latest version of WordPress. Templates in full site editing still follow the standard template hierarchy. So if you want a static homepage you should set one in _Settings > Reading_, as well as a page for your posts. With that done your _Front Page_ block template will be used to render the front page, while the _Home_ block template will be used for the posts page.
stackexchange-wordpress
{ "answer_score": 1, "question_score": 0, "tags": "block editor, full site editing" }
Hide custom column in admin template screen (Elementor) My plugin adds a custom column to admin posts and pages screens but it's also adding it to the Templates (Elementor) screen. I know users can hide this themselves, but I'd rather do it in my plugin. The page where I want to remove the column is: edit.php?post_type=elementor_library&tabs_group=library&mode=list The custom column was added using this code: add_filter('manage_pages_columns', 'customfield_add_column', 5); add_action('manage_pages_custom_column', 'customfield_add_column_values', 5, 2); add_filter('manage_posts_columns', 'customfield_add_column', 5); add_action('manage_posts_custom_column', 'customfield_add_column_values', 5, 2); function customfield_add_column($defaults){ // field vs displayed title $defaults['my_custom_field'] = __('MyField'); return $defaults; }
Use the second parameter `$post_type` passed to `manage_posts_columns` and ignore adding the column if it matches `elementor_library`: add_filter( 'manage_posts_columns', 'customfield_add_column', 5, 2 /* <= Make sure you add the 2 here to pass the second parameter to your callback */ ); function customfield_add_column( $defaults, $post_type = null ) { if ( $post_type !== 'elementor_library' ) { $defaults['my_custom_field'] = __( 'MyField' ); } return $defaults; }
stackexchange-wordpress
{ "answer_score": 2, "question_score": 0, "tags": "custom field, columns, screen columns" }
Show Site Name on WP login screen I'm trying to create a generic, re-usable function that shows the site name on the login screen. It works with just static text, but how do I pull in the site name dynamically? Here's what I've tried: function custom_login_message() { $message = '<p class="natz-login">Log in to <?php echo get_option( 'name' ); ?> </p><br />'; return $message; } add_filter('login_message', 'custom_login_message'); This is obviously wrong, but what do is use instead of `<?php echo get_option( 'name' ); ?>` ?
The function you are looking for is `get_bloginfo()`. function wpse407167_custom_login_message( $message ) { $message = '<p class="natz-login">Log in to ' . get_bloginfo('name') . '</p><br>'; return $message; } add_filter( 'login_message', 'wpse407167_custom_login_message', 99 );
stackexchange-wordpress
{ "answer_score": 0, "question_score": 0, "tags": "customization, login, bloginfo" }
Display Current Posts Category (with the most posts)? I have an post article, with a title date and the category the post is assigned to. The post is in multiple categories, but i only want to show the 'main' one its in and none of the others (for now). How do i search through all the categories the post is assigned to and only show the one with the most posts in? Therefore giving that category the idea as the main one? I assume cycling through `get_the_category` counting all the posts within all the categories assigned to this post and then picking the one with the most? $category_main = get_the_category(); //But only the one with the more posts than the others? if ( ! empty( $category_main ) ) { echo '<a href="' . esc_url( get_category_link( $category_main[0]->term_id ) ) . '">' . esc_html( $category_main[0]->name ) . '</a>'; } Thank you for any ideas :)
`get_the_category()` returns an array of `WP_Term` objects, so you already have access to the `count` property - just sort the array by it and retrieve the one with the highest count: $main_category = current( wp_list_sort( get_the_category(), [ 'count' => 'DESC' ] ) ); Check out the documentation for `wp_list_sort()`
stackexchange-wordpress
{ "answer_score": 0, "question_score": 0, "tags": "posts, categories" }
Which table (and column) has the content of configured get_post_meta? I have an already up and running WP web site. Its fully configured - some years ago :-/ Now there is the request to change the image. Somehow I don't know any longer how to do it. I managed nevertheless to find the cirtical code: <?php if (get_post_meta($curentPostID, "page_top_img", true) != ''): ?> To my understanding the code would mean: For each post there is a "meta" tag with name `page_top_img` configured. I have access to the database. Therefore the question arises where to find the configured data? i.e. Which table and which column contains the above information? Since I know the content (=result) from the web page I could do some kind of reverse engineering. Help would be highly appreciated.
Post meta data is stored in the `wp_postmeta` table, the prefix `wp_` may also be something else depending on your setup, in the `meta_value` column. * * * If there isn't a metabox in the post edit screen for updating the value, then instead of modifying the database directly you could temporarily add `update_post_meta()` call to your `functions.php` file (hooked to some action for example) to change the value - removing the function afterwards. Or if WP CLI is available, use `wp post meta update` command.
stackexchange-wordpress
{ "answer_score": 1, "question_score": 0, "tags": "database" }