INSTRUCTION
stringlengths
11
999
RESPONSE
stringlengths
0
999
SOURCE
stringlengths
16
38
METADATA
dict
Create a permalink to a pdf? I have a website where I want the permalink to my resume to be www.example.com/resume, so that whenever I send someone that link, it goes to the most recent version of my resume. But I don't want my resume to be a webpage -- I just want the permalink to send people to a PDF file, say < This way people with the www.xyz.com/resume link always see the most recent version, regardless of when I sent it. If possible, I'd also like to be able to redirect people who have the link < to be redirected to www.xyz.com/resume, and then sent to the newest version of the file. I've tried using a few plugins for this, but nothing seems to be able to generate permalinks for media files. Does anyone know how to do this?
You can accomplish the first part using the Quick Page/Post Redirect Plugin. Just set the Request URL to **/resume** and the Destination URL to **/wp-content/uploads/2021/07/Resume-v4.pdf** For the second part of your question, you can add a redirect rule to your .htaccess file: **Redirect /wp-content/uploads/2021/07/Resume-old.pdf /resume** The way you worded your question you actually would set up an infinite redirect, so I changed it here to "Resume-old.pdf".
stackexchange-wordpress
{ "answer_score": 1, "question_score": 0, "tags": "redirect, rewrite rules, media, pdf" }
Get value from shortcode to do something For a project I want to use advanced shortcodes. Normally I define shortcodes within my PHP. This way it is always the information I have in my PHP-files that I show with my shortcodes (like [shortcode]). In this project the traffic is different. I need to get information inside in my shortcode that I need to use in a variable in my PHP. This so I can use in my Wordpress editor shortcodes like [shortcode "1"] or [shortcode "2"]. This value from within the "" is a value that I will use to do something in my PHP. This way I don't need to make several shortcodes with countless options but will be way more clean. It will become a kindoff template. I know it is possible but I don't know how. I have no experience with this kind of traffic and can't find any documentation about this. Hope you guys can help me out with this.
You can find the solution for this case at <
stackexchange-wordpress
{ "answer_score": 0, "question_score": 1, "tags": "php, functions, shortcode, variables, parameter" }
How to change the layout of posts when viewing all posts by tag In Wordpress, tags are applied to our posts. When I view a post, at the bottom are the associated tags. If I click one of the tags, I am taken to a view that shows all posts with that tag. The view that is displayed shows each post's entire contents in long, narrow, unflattering columns and oversized fonts. I want to customize the layout of this. We use the Undsgn Uncode theme, and I'm not sure if it is a part of the theme, or a common setting/feature somewhere in Wordpress. Sorry, I'm a Wordpress newb and do not know where to find options that control this particular view.
As mentioned in a comment, the functionality was found in archive.php which is part of the Uncode Theme we are using. The view with posts filtered by tags is called a posts archive and Uncode provides options to change the layout of various "archives" in the theme options. It involved creating a new content block with the desired layout and then changing the theme options to use the new content block for the "Posts Archive."
stackexchange-wordpress
{ "answer_score": 1, "question_score": 0, "tags": "posts, themes, tags" }
shortcode executed in the page editor I am trying to create a really simple plugin that creates a really simple shortcode, but when I insert the shortcode in the editor, and try to save the page I get the following error: "Updating failed. The response is not a valid JSON response." I think the shortcode is being executed in the editor, because if I delete the shortcode there is no error, and I can see the echoed text for a second, when I opening the editor. this is my plugin content: <?php /** * Plugin Name: test plugin shorcode */ function vbshort_shortcode() { echo 'Hello shotcode!'; } add_shortcode('vbshort', 'vbshort_shortcode');
From the `add_shortcode()` docs: > Note that the function called by the shortcode should _never_ produce an output of any kind. Shortcode functions should _return_ the text that is to be used to replace the shortcode. Producing the output directly will lead to unexpected results. Your code should be: function vbshort_shortcode() { return 'Hello shotcode!'; } add_shortcode('vbshort', 'vbshort_shortcode');
stackexchange-wordpress
{ "answer_score": 1, "question_score": 0, "tags": "plugin development, shortcode" }
Can't Update or Delete Plugins From Wordpress I'm having trouble updating or deleting anything from the plugins folder of my Wordpress install. I've tried manually deleting the plugins via FTP, but get an error message that way. I also get an error via SSH, saying I don't have permission for those files. The plugins folder is owned and in the group www-data. Everything else is owned by the username bitnami. I'm hosted on Amazon Lightsail. How can I change the folder ownership of /Plugins/ to bitnami so that I can edit the contents?
I would check to see how your WordPress install is managed. Bitnami is a package manager, which means it probably manages updates and adding/removing plugins directly. Another solution might be running this via SSH: sudo chown -R bitnami:daemon /opt/bitnami/apps/wordpress/htdocs sudo chmod -R g+w /opt/bitnami/apps/wordpress/htdocs sudo chmod 640 /opt/bitnami/apps/wordpress/htdocs/wp-config.php This was a solution on a Bitnami Forum.
stackexchange-wordpress
{ "answer_score": 0, "question_score": 1, "tags": "plugins" }
Sort registered users by post count? (inside admin dashboard) By default, there's not option to sort users by Post count. In case you are not sure, what I'm referring to is when you click on Users > All Users inside the WP Dashnoard. I have tried searching all over the place but couldn't find the function for this simple, but yet important thing. Can anyone throw me a bone, or paste the code if you have on your own Wordpress page? I would greatly appreciate.
Try the following code: add_filter('manage_users_sortable_columns', 'my_user_sortable_columns'); function my_user_sortable_columns($sortable_columns) { $sortable_columns['posts'] = 'post_count'; return $sortable_columns; } Credit to: Add additional user fields and make them sortable in the user screen
stackexchange-wordpress
{ "answer_score": 3, "question_score": 1, "tags": "php, functions" }
Show posts from two specific category in WP_Query I've two category employee and full-time. If a post publish in both (employee and full-time) category then the post will show in his specific section. If post has only employee category, not full-time or has only full-time, not employee, then this post will not show in the post block. How can I do this? What will be the query of this relationship between two category?? Here is my code - 'tax_query' => array( 'relation' => 'AND', array( 'taxonomy' => 'category', 'field' => 'slug', 'terms' => array('employee', 'full-time'), ) ) Please help me to figure it out. I've also tried with this method, but it's not working anymore. I've the same issue. Go here for better understand understand my problem - Query only Posts from Both of Two Category?
So you want to show only posts that have both `employee` and `full-time` categories. If that is the case than you can do the following. Because you haven't posted the full query args I will only show the `tax_query` part 'tax_query' => array( 'relation' => 'AND', array( 'taxonomy' => 'category', 'field' => 'slug', 'terms' => 'employee', ), array( 'taxonomy' => 'category', 'field' => 'slug', 'terms' => 'full-time', ) ) This should do the trick
stackexchange-wordpress
{ "answer_score": 0, "question_score": 0, "tags": "posts, wp query, query posts, tax query, multi taxonomy query" }
Wordpress change title with custom dynamic I have created a custom php template file, which I use to filter results, based on user choice. I get the user's choice with the following code $bla=$wp_query->query_vars['something']; So I want to change the wordpress title, instead of the template name inside of wordpress panel, to something like "My template name dynamic- Website name" I've found this add_filter('pre_get_document_title', 'custom_title'); function custom_title($title) { return 'Test New Title'; } And it changes the title, however it doesn't show the contents of the $bla. If you echo it few lines down the code it works. I believe that is because I have to place this filter before the get_header() of the template file. Any advice?
Move the check for the query var into your title filter: add_filter('pre_get_document_title', 'wpse392764_qv_template_title' ); function wpse392764_qv_template_title( $title ) { $foobar = get_query_var( 'foobar' ); if( empty( $foobar ) ) return $title; return sprintf( __( '%s Dynamic - %s', 'wpse392764' ), esc_html( $foobar ), get_bloginfo( 'name' ) ); }
stackexchange-wordpress
{ "answer_score": 0, "question_score": 0, "tags": "templates" }
API for getting plugin core compatibility? I’m looking for a way to determine which version of Wordpress a plugin has been tested to work with. Only way I’ve found is by looking at the plugin’s homepage. I can scrape that but I’m wondering if there is an API or some other better way to get this information.
This should get you what you are looking for: Wordpress.org API for Plugins Here's the full documentation: Wordpress.org API Doc
stackexchange-wordpress
{ "answer_score": 2, "question_score": 1, "tags": "plugins" }
Query with a meta value inside a given range Quick question: I would like to retrieve some pages/posts with a meta value inside a range, eg) `$min<$meta_value<$max` for ordinary $meta_value there was a way to get pages/posts like this: $args = array( 'meta_key' => $key, 'meta_value' => $meta_value, //$min<$meta_value<$max 'post_type' => 'page', 'post_status' => 'publish', ... ); $pages = get_pages( $args ); What is the best solution? should I first get them all and check them in an if condition or should I use `$wpdb->get_results($sql,OBJECT)` or is there a better way? From SQL we have: SELECT column_name(s) FROM table_name WHERE column_name BETWEEN value1 AND value2; Does the `WP_query` class have a method to use the `BETWEEN` keyword inside a query?
In this situation you will want to use the `meta_query` parameter, an example: $args = array( 'post_type' => 'page', 'post_status' => 'publish', 'meta_query' => array( array( 'key' => $key, 'value' => array($min, $max), 'compare' => 'BETWEEN', ), ), ); $query = new WP_Query( $args ); **The possible values for for the 'compare' key are:** * "=" * "!=" * ">" * ">=" * "<" * "<=" * "LIKE" * "NOT LIKE" * "IN" * "NOT IN" * "BETWEEN" * "NOT BETWEEN" * "EXISTS" (only in WP >= 3.5) * "NOT EXISTS" (only in WP >= 3.5) * "REGEXP" (only in WP >= 3.7) * "NOT REGEXP" (only in WP >= 3.7) * "RLIKE" (only in WP >= 3.7) Default value is "=". **Useful reading:** * < * <
stackexchange-wordpress
{ "answer_score": 1, "question_score": 1, "tags": "wp query, query posts" }
How to remove an action that is added inside a class Here is the code in short that is coming from a plugin: class Post_Views_Counter_Columns { public function __construct() { add_action( 'wp', array( $this, 'admin_bar_maybe_add_style' ) ); } } I want to remove this `admin_bar_maybe_add_style` function. I am trying with following code in my **child theme's functions.php** remove_action( 'wp', array( 'Post_Views_Counter_Columns', 'admin_bar_maybe_add_style' ) ); It's not working. Any suggestions?
I don't understand any of it but it seems to work just fine. Thank you @Buttered_Toast for mentioning the useful thread. add_action("init", function() { global $wp_filter; foreach($wp_filter["wp"][10] as $id => $filter) { if(is_array($filter["function"]) && count($filter["function"]) == 2 && get_class($filter["function"][0]) == "Post_Views_Counter_Columns" && $filter["function"][1] == "admin_bar_maybe_add_style") { remove_action("wp", $id); } } }, 99);
stackexchange-wordpress
{ "answer_score": 1, "question_score": 0, "tags": "actions" }
Get all image in media Gallery with alt/title? Is there a way to fetch the **ALT/TITLE** of ALL images in the media gallery? I think this would be an easy way for a website to have a Pictures page that just pulls all of the images from the media gallery, granted it would only be necessary in certain scenarios. I don't need instructions on how to create a Pictures page, just how to pull all of the image URLs. Thanks!
<?php /* * Template Name: Gallery Page */ $query_images_args = array( 'post_type' => 'attachment', 'post_mime_type' => 'image', 'post_status' => 'inherit', 'posts_per_page' => - 1, ); $query_images = new WP_Query( $query_images_args ); ?> <?php get_header();?> <div class="main"> <div class="row"> <?php foreach ( $query_images->posts as $image ) {?> <div class="col-md-3"> <?php echo wp_get_attachment_image( $image->ID,'thumbnail' );?> </div> <?php }?> </div> </div> <?php get_footer();?>
stackexchange-wordpress
{ "answer_score": 0, "question_score": 0, "tags": "plugins, images, attachments, attachment fields to edit" }
Submitting a block to the .org repo: do I submit compiled code, or source code? I plan on submitting a Gutenberg block to the repo. What am I supposed to submit? Only the compiled code is distributed. Based on how the SVN repo works, it seams I should NOT be submitting the source code.
Have a look at the handbook. And you're right, put the code to distribute there. I'm quoting the handbook: > SVN and the Plugin Directory are a release repository. Unlike Git, you shouldn’t commit every small change, as doing so can degrade performance. Please only push finished changes to your SVN repository.
stackexchange-wordpress
{ "answer_score": 1, "question_score": 0, "tags": "block editor, svn, plugin repository" }
Fullscreen Page Background without Plugin I am using the Advanced Layout builder for editing pages in the Enfold theme. I've seen many solutions via code editing or plugin additions, but I am behind a controlled environment and do not have access to FTP (access to functions.php, files, etc) nor WP plugins. The home page can be set to a fullscreen background via the `Theme > Customize > Appearance` , but I want to add a _fullscreen_ background image to other pages. The only option I see is in the settings of a `1/1 column > Styling > Background Image`. But this background is bounded and does not fill the full-width of the page. How can I add a full-width background image without a plugin, or functions.php?
Okay, so I found a solution by using a different type of section. The issue was having was the max width was capped at the container's width which could not be set and looked like this: ![enter image description here]( But after changing the section type from a 1/1 to a color section, I was able to have the background image fill the full-width of the page like this: ![enter image description here]( Code wise looks like: /* Color section container width */ #section-container-width .container { width: 100% !important; min-width: 100%; padding: 0; margin: 0; }
stackexchange-wordpress
{ "answer_score": 0, "question_score": 0, "tags": "images, custom background, screen layout" }
Custom Email via Hook only for completed order I wanted to customize completed order with some extra information. To do so, I added this in functions.php add_action( 'woocommerce_email_before_order_table', 'mm_email_before_order_table', 10, 4 ); function mm_email_before_order_table( $order, $sent_to_admin, $plain_text, $email ) { echo '<p>extra information</p>'; } How can I ensure this to work only for completed emails and not other emails (e.g. order creation) Thank you so much
If your code works but it works for all emails you can add a check for only completed orders like this add_action( 'woocommerce_email_before_order_table', 'mm_email_before_order_table', 10, 4 ); function mm_email_before_order_table( $order, $sent_to_admin, $plain_text, $email ) { // if not completed order, exit if ($email->id != 'customer_completed_order') return; echo '<p>extra information</p>'; }
stackexchange-wordpress
{ "answer_score": 0, "question_score": 0, "tags": "woocommerce offtopic, email, order" }
What is the easiest way to rename a plugin (and also avoid plugin updates) I have a few customers and they absolutely want me to make changes within plugins which do NOT offer hooks etc. I checked it - only way is to modify the plugin directly. So: I want to know what is the easiest way to rename the plugin, to achieve: 1. avoid getting plugin updates, i.e. block them 2. to make clear that modifications by me were done in this plugin Just rename the folder and the header in the main file? Or can this break anything? Thanks!
Rename: * the plugin folder * the Plugin Name in whatever php file loads first * the name at the top of the readme.txt If it is a premium plugin, you need to remove or cripple any external checks. You may also want to include an `init` check for an activated version of the original plugin and if found, deactivate.
stackexchange-wordpress
{ "answer_score": 1, "question_score": 0, "tags": "plugins, plugin development" }
How to check $_GET isset for a parameter and value? Let's say I have a link: < I know how to do something if a specific parameter exists : <?php if(isset($_GET['name'])) : ?> What I want is to use `if` for both, parameter and value. Basically I want to do like this: <?php if(isset($_GET['name, john'])) : ?> Above is just an exmaple. It's doesn't work. Can anyone guide to the right code for this? Thanks.
Try this- <?php if( isset( $_GET['name'] ) && $_GET['name'] == 'john' ) : ?> // some code // some code // some code <?php endif; ?> You need to check if `$_GET['name']` exists AND if its value is `john`.
stackexchange-wordpress
{ "answer_score": 1, "question_score": 0, "tags": "php" }
padding not working I want to add some space above the heading. I have added: padding-top: 200px !important; ![The problem!]( Appriciate your help to solve this issue. Also I wonder how can I add spaces (padding top/bottom) to h1,2,3,4,5 & 6 tags so when ever I apply heading to a text, the padding should be applied automatically instead of adding additional class or style. I don't want to use line-height? Note: I'm using Elementor Pro + Hello Theme. Thanks
`<span>` tags is a inline element and inline elements don't react well with padding. You can target the **h1** \- **h6** as you said, but if you want to target the `<span>` you will need to add `display: inline-block;` as well for it to work with padding. Also, this has nothing to do with WordPress as this is a pure CSS question, for future questions that don't involve WP use stackoverflow.
stackexchange-wordpress
{ "answer_score": 0, "question_score": 0, "tags": "css" }
Limit Gutenberg blocks available to users to choose from I am using the `allowed_block_types_all` filter to choose certain blocks the users can choose from. I have just added one here as an example. This works fine but my issue comes in when trying to choose embeds. add_filter( 'allowed_block_types_all', 'usr_allowed_block_types' ); function usr_allowed_block_types( $allowed_blocks ) { return array( 'core/paragraph', 'core-embed/twitter' ); } I see the paragraph but not twitter. If I add `core/embed` then I get ALL embeds which I really don't want.
In the functions.php file I added add_filter( 'allowed_block_types_all', 'func_allowed_block_types' ); function func_allowed_block_types( $allowed_blocks ) { return array( 'core/embed' ); } Then in my plugin I added this JS to the javascript file to enable only the embed blocks I wanted (Twitter, youTube and Vimeo) wp.domReady( function() { const allowedEmbedBlocks = [ 'twitter','youtube', 'vimeo' ]; wp.blocks.getBlockType( 'core/embed' ).variations.forEach( function( blockVariation ) { if ( allowedEmbedBlocks.indexOf( blockVariation.name ) === -1 ) { wp.blocks.unregisterBlockVariation( 'core/embed', blockVariation.name ); } } ); } );
stackexchange-wordpress
{ "answer_score": 2, "question_score": 1, "tags": "posts, block editor, blog" }
Activate Plugin Automatically After Set Time please how do I activate a plugin after a set period of time automatically. For example, let's say I want to activate Jetpack automatically after 3 weeks. Thanks
Add this to the `functions.php` file of your active (child) theme- add_action( 'init', 'wpse_393267_activate_plugin' ); function wpse_393267_activate_plugin() { if( !function_exists( 'is_plugin_active' ) ) { include_once ABSPATH . '/wp-admin/includes/plugin.php'; } $plugin_to_activate = 'jetpack/jetpack.php'; // plugin-dir/plugin-file.php $date_to_activate = '2021-08-13'; // YYYY-MM-DD if( is_plugin_active( $plugin_to_activate ) ) return; if( time() >= strtotime( $date_to_activate ) ) { activate_plugin( $plugin_to_activate ); } } Change the `$plugin_to_activate` and `$date_to_activate` as you want.
stackexchange-wordpress
{ "answer_score": 0, "question_score": 0, "tags": "plugins, plugin development, wp cron, cron, scripts" }
Change URL without reload Ajax Can I change pages with Ajax + Wordpress without reloading? Only articles related to dynamic post display or AJAX pagination are available on the web. Where can I find out about the use of AJAX in 'wp_nav_menu " Here is my inspiration: (see their navigatio) LINK
The site you linked to isn't updating the nav menu with AJAX, rather, when you click a link they load the target via JS then swap the entire page for the new page. A little bit of trickery with pushState ensures the URL in the address bar changes and back/forward is preserved. Take a look at the term _**PJAX**_ , there are JS libraries that implement it, and it may be a more useful search term. Otherwise your options are limited. If you're building a SPA, you will want to construct your menu and use browser history/current URL to figure out which element to style
stackexchange-wordpress
{ "answer_score": 1, "question_score": 0, "tags": "ajax" }
Slug for custom post type I use both pages and blog posts on my site. Pages get the URL example.org/%postname%/, and based on Permalink settings, posts get the URL example.org/blog/%postname%/. Perfect. I have a custom post type used by another group on my site for their web pages. In registering the post type, I have a rewrite slug for them: `'rewrite' => array('slug' => 'ncfpw'),` However, their pages are getting the URL example.org/blog/ncfpw/%postname%/ How can I get rid of "blog" in their URLs? Somehow it seems Wordpress sees the custom post type as posts, not pages?
> Somehow it seems Wordpress sees the custom post type as posts, not pages? No, but your permalink structure (for the default `post` post type) that you set via the Permalink Settings admin page contains (or starts with) `blog/` and by default, it will also be prepended to permalinks for custom post types, unless the post type sets the `with_front` argument to `false`. Therefore, > How can I get rid of "blog" in their URLs? Just set the `with_front` to `false`: 'rewrite' => array('slug' => 'ncfpw', 'with_front' => false), And then flush the rewrite rules by simply visiting the Permalink Settings page.
stackexchange-wordpress
{ "answer_score": 2, "question_score": 0, "tags": "custom post types, slug" }
Unexpected character and syntax error on wp-includes/formatting.php I am getting an error on my WordPress website after changing the server. it's working on cPanel but not working on the AWS server. I haven't change anything in this file. ![enter image description here]( ![enter image description here](
I don't know how I got this gray code on the formatting.php page. I found this code in more than 3 places. I download the latest version of WordPress again and updated the formatting.php and It's starting working again. ![enter image description here](
stackexchange-wordpress
{ "answer_score": 0, "question_score": 0, "tags": "plugins, plugin development" }
customizer refresh breaks with this code but I don't understand why Below code is a portion of my "wp_nav_menu" code. I don't understand why the 4th part below, the 'menu' section breaks the "customizer refresh". It makes the refresh in customizer not function when editing menus. But if I delete the 'menu' line completely, then the customizer functions normal/perfect. Fine with me, I will delete it. But can someone explain why the line breaks the customizer refresh? wp_nav_menu( array( 'container' => 'nav', 'container_id' => 'site-navigation', 'container_class' => 'main-navigation', 'menu' => 'primary',
The `menu` argument is used to output a particular menu item to a particular location in the theme. Suppose you created and a menu in the Dashboard and want it to load in the main navigation bar without setting it in the 'Manage Locations' tab in the Dashboard. In that case, you will enter the menu ID/name/slug/object in the `menu` argument of `wp_nav_menu`. Check out the codex - < The `theme_location` will be ignored in this case. Regarding your issue, you have entered 'primary' in the menu argument. You need to verify if any of the menus you created have 'primary' as slug or name.
stackexchange-wordpress
{ "answer_score": 0, "question_score": 0, "tags": "theme customizer" }
Output a specific link in Wordpress post if the single post's category's name contain certain word I want to output a specific link in every post, depending on the post's category. For example, if a post is in "travel" category, then the link to < will be displayed in this post. If a post is in "hotel" category, then the link to < will be displayed in this post. I tried this code <?php $category = get_the_category(); $firstCategory = '$category[0]->cat_name'; if (strpos($firstCategory, 'travel') !== false) { echo '<a href=" travelbooking</a>'; } if (strpos($firstCategory, 'hotel') !== false) { echo '<a href=" hotelbooking</a>'; } else { echo '<a href=" homepage</a>'; } ?> But it doesn't work, any suggestion?
You should remove the single quotes around the expression otherwise it will be treated as a string. > `$firstCategory = '$category[0]->cat_name';` Should be changed to: $firstCategory = $category[0]->cat_name; Then you can try basic debugging like printing the output of the `$category` and `$category[0]->cat_name`.
stackexchange-wordpress
{ "answer_score": 1, "question_score": 0, "tags": "functions, taxonomy" }
unique url access control basically I'd like to have my page accessible by only certain listed users which we'll make a unique code. for example user A will be able to access with an URL like: > www.mysite.com/?u=UserA but when someone accessed with only _www.mysite.com_ we'll direct to a **" you don't have access"** page. of course if user A sent their unique link to other people, others will be able to access, but that's ok for my page. the reason is that when User A access this page, we'd want to show a " **Welcome to the page User A** " text, and we'll retrieve this creds from the link. can we use PHP for this? any kind of help is appreciated. thank you in advanced :)
You can just check if query string "u" exists, else redirect to your "you don't have access" page. So something like this: if ( isset($_GET('u')) ) { // SHOW YOUR CONTENT } else { header('Location: die(); }
stackexchange-wordpress
{ "answer_score": 0, "question_score": 0, "tags": "urls, user access" }
After database migration, theme mods don't show My Wordpress installation has only one theme which is active. The `wp_option` entry for it shows there are 31 theme mod entries. a:31:{s:18:"custom_css_post_id";i:5248;s:30:"theme_settings_api_keys_google";s:39:"xxx.....etc..";s:28:"theme_settings_xxx";........etc...etc...etc....;s:11:"custom_logo";i:5810;} however when I run `get_theme_mod( 'my_mod_x' ))` nothing comes is returned. So too when I run on the command line: `wp theme mod get --all --allow-root`. All I get is: +--------------------+-------+ | key | value | +--------------------+-------+ | custom_css_post_id | 5248 | +--------------------+-------+ Can anyone tell me what would cause WordPress to think there is only one theme mod when there is supposed to be many?
The problem was that one if the the serialized string lengths did not match its true string length. One of the migration steps was to change the domain name in the database SQL file with: `sed -i 's/old-domain-name/new-domain/g' db-dump.sql` One of the theme mods was a string that contained the old domain name. When it was changed to the new domain name, the length of the string was not adjusted to to match the new string length. Therefore, WordPress was unable to properly read the theme mods. Lesson: Be careful when doing a global find and replace on the db-dump.sql file!
stackexchange-wordpress
{ "answer_score": 1, "question_score": 0, "tags": "database, migration, get theme mod" }
API response to be stored locally Is it possible to refactor the code so that the API response would be stored locally for one day, instead of retrieving the data from the API each time the page loads? <?php // Assume "$list_api->get_items()" connects to an API. $list_items = $list_api->get_items(); if(!empty($list_items)) { foreach($list_items as $list_item) { ?> <div class="item-container"> <h2><?php echo $list_item['title']; ?></h2> <p><?php echo $list_item['paragraph']; ?></p> </div> <?php } } ?>
Sure, you can store it in a transient for a day. <?php $list_items = get_transient( 'my_list_items' ); if ( false === $list_items ) { // Assume "$list_api->get_items()" connects to an API. $list_items = $list_api->get_items(); set_transient( 'my_list_items', $list_items, DAY_IN_SECONDS ); } if(!empty($list_items)) { foreach($list_items as $list_item) { ?> <div class="item-container"> <h2><?php echo $list_item['title']; ?></h2> <p><?php echo $list_item['paragraph']; ?></p> </div> <?php } } ?> ## References * `get_transient()` * `set_transient()`
stackexchange-wordpress
{ "answer_score": 2, "question_score": 1, "tags": "php, wp query" }
Use dedicated functions In the following page template, an additional JS script (“carousel.js”) and additional CSS file (“carousel.css”) should be loaded. How to run these files using WordPress dedicated functions? <?php /** * Template Name: Full Width Page * * @package WordPress */ get_header(); while ( have_posts() ) : the_post(); the_content(); if ( comments_open() || get_comments_number() ) { comments_template(); } endwhile; get_footer();
You'll want to enqueue the script in your functions.php (If this is in a plugin, you could do a little differently). Here's a sample: function owl_scripts() { wp_enqueue_script( 'owl-carousel', get_stylesheet_directory_uri() . 'js/carousel.js', array( 'jquery' ), '', true ); wp_enqueue_style( 'owl-style-min', get_stylesheet_directory_uri() . 'css/carousel.css' ); } add_action( 'wp_enqueue_scripts', 'owl_scripts' ); This is assuming: 1. You're using a child theme. 2. You put the carousel.js in the directory 'your-child-theme/js'. 3. You put the carousel.css in the directory 'your-child-theme/css'.
stackexchange-wordpress
{ "answer_score": 0, "question_score": 0, "tags": "wp query" }
Redirecting non-logged in users trying to view Group pages but not the Group directory We are looking to redirect all Groups pages (but not the Groups directory page /groups/) in BuddyPress for non-logged in users to the /register/ page. We are currently using this snippet for member profiles in our functions.php file: /*** Redirect non logged-in users to registration page if they visit a profile page ***/ function gwangi_bp_logged_out_page_template_redirect() { if( ! is_user_logged_in() && bp_is_user() ) { wp_redirect( home_url( '/register/' ) ); exit(); } } add_action( 'template_redirect', 'gwangi_bp_logged_out_page_template_redirect' ); Is there a way this can be modified to also include Group pages (excluding the Groups directory /groups/)? We are unsure and inexperienced on how to go about this. Any help on this would be appreciated! Thanks.
It looks like `bp_is_group()` is "does the current page belong to a single group" (as opposed to `bp_is_groups_directory()`): /*** Redirect non logged-in users to registration page if they visit a profile page or a group page other than the groups directory ***/ function gwangi_bp_logged_out_page_template_redirect() { if( ! is_user_logged_in() && ( bp_is_user() || bp_is_group() ) ) { wp_redirect( home_url( '/register/' ) ); exit(); } } add_action( 'template_redirect', 'gwangi_bp_logged_out_page_template_redirect' ); There's more bp_is_* functions in src/bp-core/bp-core-template.php.
stackexchange-wordpress
{ "answer_score": 0, "question_score": 0, "tags": "buddypress, wp redirect" }
meta_query not working I have a custom dropdown field in my media uploader which saves to the posts meta. Now I'm trying to get all images with a specific value with a meta_query. The variable `$author` is exactly the value that is saved in the postmeta in MySQL. $rd_args = array( 'meta_query' => array( array( 'key' => 'post_slider_author', 'value' => $author ) ) ); $rd_query = new WP_Query( $rd_args ); $mh_posts = $rd_query->posts; As you can see in the screenshot there is a value assigned to the meta `post_slider_author` and '1139' is also the correct ID. Unfortunately the query stays empty. ![enter image description here]( Additional: I tried to disable all plugins but it had no effect. Normal queries work just fine.
I change it to `get_posts()` instead of `new WP_Query` and it works just fine. No idea what's the problem with the query.
stackexchange-wordpress
{ "answer_score": 0, "question_score": 0, "tags": "query, meta query" }
WebP issue on new 5.8 version the new WordPress 5.8 version includes WebP Image support which is great. But some browsers (safari older than version 14) do not support them. How can it be done that in this case it will fall back to the .jpg file? I thought wordpress would manage this but it does not. Thanks.
You can't, there's a filter to convert everything to jpeg on upload or everything to webp, but short of installing a 3rd party service to figure it out on the fly there is no fallback solution that serves webp to some and jpeg to others > I thought wordpress would manage this but it does not. Correct, WP does not handle this, and there is no canonical solution for this. If you need to support browsers that do not support webp, don't use webp, convert everything to JPEG via filters on upload, or use a 3rd party CDN service that will optimise images on the fly.
stackexchange-wordpress
{ "answer_score": 0, "question_score": 0, "tags": "browser compatibility" }
How to get the URL of a sitemap that contains a certain post? I am searching for a way to "detect" in which sitemap a post is located in but I cannot find any solution to this problem, nor does any SEO plugin or Cache plugin provide any way or wrapper function to return this? Essentially I'm looking for a function that takes a $post_id or a $post object and can return a sitemap URL in which that post is located or an array of sitemaps (if it shows up in multiple sitemaps). Any help is greatly appreciated.
I achieved it using this simple query <?php $chunks=array_chunk( get_posts([ 'fields'=>'ids', 'posts_per_page'=>-1, 'post_type'=>[$post->post_type], 'orderby'=>'ID', 'order'=>'ASC' ]), wp_sitemaps_get_max_urls('post') ); foreach($chunks as $key => $chunk) { if(!in_array($post->ID,$chunk)) continue; var_dump(get_sitemap_url('posts',$post->post_type,$key + 1)); break; }
stackexchange-wordpress
{ "answer_score": 0, "question_score": 0, "tags": "cache, sitemap" }
How to create templates for a custom module to show on the front end within my theme? I'd like to create a simple plugin with a form on the front end which submits the value of 3 fields into a DB table. For the plugin, I've been using this answer: < What I can't get working now, is a template. Within the main plugin file, I've added: add_action( 'gm_virtual_pages', function( $controller ) { // first page $controller->addPage( new \WEBP\Management\Page( '/custom/page' ) ) ->setTitle( 'My First Custom Page' ) ->setTemplate( 'custom-page-form.php' ); } ); And my `custom-page-form.php`: <?php echo "Test Echo"; ?> <p>Test</p> <p>Echo</p> The title is being displayed (My First Custom Page). But not my Test Echo. How does a correct / working template file have to look like?
Templates in wordpress just needs to be valid PHP files. You need to place your template inside theme ( or child theme directory ). Have you placed the template in plugin directory ? if yes it won't work. < > Template file set via setTemplate must be in theme (or child theme) folder. For more details of the issue you can try turning debug more on in wordpress and enable error reporting.
stackexchange-wordpress
{ "answer_score": 1, "question_score": 0, "tags": "plugin development, templates" }
add role on WordPress in PHP on a second database I have a site A (a store) where once the purchase is made the new user has to register in site B (a members area). To do this I connected the second database and also managed to pass the various info with the following method: $DB_MEMBERSHIP->insert( 'wpvm_users', array('user_login' => $user_login, 'user_pass' => $user_pass, 'user_nicename' => $user_nicename, 'user_email' => $order_billing_email, 'user_registered' => $user_registered, 'display_name' => $display_name) ); Now though, I'm wondering how it's possible to add the role. How can I do that? I use the following code to insert the user meta: $id_user = $DB_MEMBERSHIP->get_var("SELECT ID FROM `wpvm_users` WHERE user_email = '" . $order_billing_email . "'"); $DB_MEMBERSHIP->insert('wpvm_usermeta', array('user_id' => $id_user, 'meta_key' => 'first_name', 'meta_value' => $order_billing_first_name));
I managed to solve after several attempts using the following code: // Insert the role $role = array('gold_role' => 1); $serialized_role = serialize($role); $DB_MEMBERSHIP->insert('wpvm_usermeta', array('user_id' => $user_id, 'meta_key' => 'wpvm_capabilities', 'meta_value' => $serialized_role)); It works very well and doesn't slow down the shopping experience.
stackexchange-wordpress
{ "answer_score": 0, "question_score": 0, "tags": "php, database, sql" }
How to edit dashboard search posts button texts for my CPT? I am new to WordPress Development. Can I change texts of filter search box button ? ![enter image description here](
When registering the post type you should set the `search_items` label: register_post_type( 'question', array( // etc. 'labels' => array( // etc. 'search_items' => 'Search Questions', ), ) ); You can see the full list of labels that you can set here.
stackexchange-wordpress
{ "answer_score": 1, "question_score": 1, "tags": "filters, search, dashboard" }
Unable to create a WordPress.org account While I tried registering on wordpress.org, I did not receive any confirmation email from the website. When I tried again, it told me that: > That email address already has an account. The registration is still pending, please check your email for the confirmation link. Resend confirmation email. To double check, I checked the spam box as well. I've tried different emails again and again without success. I would appreciate any help you can provide. For details, see the image below: ![enter image description here](
I sent an email to **[email protected]** , and they resolved the issue. They replied with the following reason: **Why This Happened** Due to the high volume of mail and signups we have at WordPress.org, and the sadly high number of fake accounts, we have a very complex system to try and catch bad actors before they make life miserable for everyone. Sometimes that tool gets a little exuberant and false-flags. We are a actively working to improve this.
stackexchange-wordpress
{ "answer_score": 2, "question_score": -1, "tags": "wordpress.org" }
How to get path or root of plugin folder, not file or dir? I want to include one file from the plugin root to somewhere in the plugin folder. Folder structure: /plugin /folder <- Can't 'esacpe' from this folder to root /otherfolder /req-file-to-here.php // fetch here /req-file-from-here.php // send from here What to exactly type in file `req-file-to-here.php` ? I have tryed something like this: `require plugin_dir_path( __FILE__ ) . '..path to file';` or `require plugin_dir_path( __DIR__ ) . '..path to file';` Not working. Help :)
How about just define a constant that stores the plugin's root path? > **Define path constant** > > For calling numerous files, it is sometimes convenient to define a constant: > > > define( 'MY_PLUGIN_PATH', plugin_dir_path( __FILE__ ) ); > include( MY_PLUGIN_PATH . 'includes/admin-page.php'); > include( MY_PLUGIN_PATH . 'includes/classes.php'); > // etc. > — See < So in your main plugin file: define( 'MY_PLUGIN_PATH', plugin_dir_path( __FILE__ ) ); And then in `folder/otherfolder/req-file-to-here.php`, do: require MY_PLUGIN_PATH . 'req-file-from-here.php'; Alternatively, you could define just the path to the main plugin file: define( 'MY_PLUGIN_FILE', __FILE__ ); And then in `folder/otherfolder/req-file-to-here.php`, do: require plugin_dir_path( MY_PLUGIN_FILE ) . 'req-file-from-here.php';
stackexchange-wordpress
{ "answer_score": 2, "question_score": 0, "tags": "plugins, plugin development, directory, paths" }
adding wp-cli commands to plugin: how to document to users? I'm adding wp-cli support to a plugin of mine. Is there an accepted way of letting my users know they can use wp-cli with my plugin? I can put stuff in my readme.tx of course, and I can put an explanation on my admin page, and I will do those things. But, is there a particular tag in the plugin registry? A conventional format for the readme.txt and/or admin page explanations? (I know about `wp mycommand help` : the built-in help once a user finds their way to the cli.)
There's the `wp-cli` tag that is being used in WordPress plugin directory, but it is not super popupar (less than 500 plugins seem to use it). `wpcli` is not even close with less than 20. In general you've listed all the other ways that you can inform your users unintrusively about the presence of a WP-CLI command with your plugin. You could, of course, add an article in your plugin's website, the extra documentation that you might have, in the newsletter for the plugin, etc., but this is all extra efforts for someone who's making money out of it or insists on making it a well-known fact by everyone.
stackexchange-wordpress
{ "answer_score": 2, "question_score": 0, "tags": "plugin development, wp cli, readme" }
Syntax Issue: How Do I Call A Custom Field Inside a ForEach Statement? I used the ACF (Advanced Custom Fields) plugin to create two custom fields (news_source and news_link) for a new post type (news). I'm trying to use the following code to display the title and the two new fields on my home page. It pulls the title but it doesn't pull the custom fields even though I can see the custom fields on the single.php page. I think my syntax is wrong for the second echo statment because it isn't returning a value between the paragraph tags. What did I do wrong? <ul> <?php $recent_posts = wp_get_recent_posts(array('post_type'=>'news')); foreach( $recent_posts as $recent ) { echo '<li><a href="' . get_permalink($recent["ID"]) . '" title="Look '.esc_attr($recent["post_title"]).'" >' . $recent["post_title"].'</a> </li> '; echo '<p>' . get_field($recent["news_source"]) . '</p>'; } ?> </ul>
<ul> <?php $recent_posts = wp_get_recent_posts(array('post_type'=>'news')); foreach( $recent_posts as $recent ) { echo '<li><a href="' . get_permalink($recent["ID"]) . '" title="Look '.esc_attr($recent["post_title"]).'" >' . $recent["post_title"].'</a> </li> '; echo '<p>' . get_field("news_source",$recent["ID"]) . '</p>'; } ?> </ul> It looks your are passing get field parameters incorrectly. I assumed "news_source" is your custom field name in acf.
stackexchange-wordpress
{ "answer_score": 2, "question_score": 0, "tags": "custom field" }
get_the_author_meta( $field, 0 ) returns the administrator $field Just discovered that the `get_the_author_meta( 'birth_date', 0 )` returns the administrator birthdate. The same happens with other `$field` parameters for `$user_id = 0`. Is this an expected behavior for this function?
Directly on the question - no, the `get_the_author_meta()` function is not supposed to return you by default the birthday date when you provide 0 for user ID, as it is not a default user meta field. Yet, providing 0 is the same as not providing a user ID at all, hence the function tries to get the author ID from the global `$authordata` variable. Looking at the bottom of the code of the function, there is this last line in it, which suggests something (a plugin or the theme) might be messing with you: return apply_filters( "get_the_author_{$field}", $value, $user_id, $original_user_id );
stackexchange-wordpress
{ "answer_score": 2, "question_score": 1, "tags": "author, user meta" }
Is there a way to download only the Rest API part of WordPress? Is there a way of downloading only the `Rest API` part of WordPress and not all the old PHP files?
WP REST API depends on WordPress, as it is just another interface for interacting with its other APIs. If BackPress (< was still in development, you could have had some chance with it, but it seems the project is abandoned. The plugin that was merged with WordPress Core is available here: < but is also abandoned, so you will not get the latest stuff that's in 5.8. I don't know whether this would be of help to you, as I don't know your main goal, but I would rather try to extract whatever I need from nowadays' Core, than messing with the old plugin.
stackexchange-wordpress
{ "answer_score": 1, "question_score": 0, "tags": "rest api, wp api" }
Register PODS Custom Field with WPGraphQL I've created a Custom Post Type called 'Item' and added a multi-upload file/image/video field type but I'm not able to figure out how to register that custom field with WPGraphQL. Here's how I registered my CPT with WPGraphQL: add_filter( 'register_post_type_args', function( $args, $post_type ) { if ( 'item' === $post_type ) { $args['show_in_graphql'] = true; $args['graphql_single_name'] = 'item'; $args['graphql_plural_name'] = 'items'; } return $args; }, 10, 2 ); Any suggestions or can someone point me in the right direction for documentation? I've gotten different answers in my search and nothing has worked so far. Thanks!
This WPGraphQL recipe covers how to set up a new field using `register_graphql_field()` (function doc) but it doesn't have any examples on how to pass in image/file fields. If I were doing this for a quick project, I would just output the information I needed without getting too complicated/deep into the API. But as it turns out.. Some good news if you're looking to make things easier for yourself -- work on Pods 2.8 (in beta right now) has enabled more WPGraphQL capability for Pods. I was able to build out an entire Pods Pro WPGraphQL Add-On which allows you to set up GraphQL access for whole Pods as well as all/individual fields in that Pod. I put extra attention into making sure that relationships and file fields are well represented in the GraphQL structure, you should check out the demo video.
stackexchange-wordpress
{ "answer_score": 0, "question_score": 0, "tags": "plugins, custom post types, custom field, pods framework" }
Change Page Title I have successfully changed the name of a specific page using this code in my functions.php file: add_filter('pre_get_document_title', 'change_my_property_title'); function change_my_property_title($title) { if ( is_page('property') ) { return 'Property'; } return $title; } My problem is I can't figure out how to change the name to an actual php variable that is on the property page. I am pulling property information from a json url and would like the address to be the title. If I try to point to the variable in my return statement nothing comes up. Here is the page I'm working on:
I got it! By using the functions.php page I wasn't able to use variables defined on the page I wanted to create custom titles for. I ended up adding the below code to my custom page php. <?php $newtitle = ucwords($mlsa->StreetNumber . ' ' . $mlsa->StreetName . ' ' . $mlsa->StreetSuffix.', '. $mlsa->City); ?> <script>document.title = "<?php echo $newtitle; ?>";</script> or a more simple version: <?php $newtitle = $someVariable; ?> <script>document.title = "<?php echo $newtitle; ?>";</script>
stackexchange-wordpress
{ "answer_score": 0, "question_score": 0, "tags": "functions, title, json, variables" }
How to Display Shortcode's Content after Short Product Description? This is my Shortcode: `[mbv name=”product-info”]` And i want to display this shortcode's content after WooCommerce Short Product Description How can i do it?
**I got a solution from below codes:** add_filter('woocommerce_short_description', function ($description) { if (! is_product()) { return; } return $description.do_shortcode('[mbv name="product-info"]'); });
stackexchange-wordpress
{ "answer_score": 0, "question_score": 0, "tags": "shortcode" }
How to display html element and php string in the same line? Hope someone can help me with this. This is my code: function swh_woocommerce_store_credit_shortcode() { $store_credits = swh_woocommerce_get_store_credits(); echo "<span style= 'display: inline;'>Remaining Credit:</span>"; return wc_price($store_credits); } add_shortcode( 'swh_store_credit_total_value', 'swh_woocommerce_store_credit_shortcode' ); I'm trying to display echo and return in the same line. i. e. `Remaning Credit: $80` and not Remaining Credit: $80 Thanks!
You must not use use `echo` or `print` in a shortcode function. The echoed string will be printed out immediately when the content is processed, which is almost always too early. So in your function you should just return the string without using `echo`: function swh_woocommerce_store_credit_shortcode() { $store_credits = swh_woocommerce_get_store_credits(); return "<span style= 'display: inline;'>Remaining Credit:</span>" . wc_price($store_credits); }
stackexchange-wordpress
{ "answer_score": 0, "question_score": 0, "tags": "shortcode, css" }
How to add CSS to head by php through echo self::css(); The tutorial < gives a method for changing color by WordPress Customizer (Color control). It changes the color through the following code /** * For hooking into `wp_head` mostly to output CSS */ public static function output() { echo '<style id="hero-css">'; echo self::css('.hero', 'background-color', 'hero_background_color'); echo '</style>'; } When I do this, I get a 500 error. Am I missing something? Edit: Right now I have a complete working `WP_Customize_Color_Control` and its `$wp_customize->add_setting` works with `refresh` right now, I want the transport to be `postMessage`.
This tutorial seems to create a whole class for working with css. How about starting with a very basic example and working from there. In order to add `<style>` to `<head>` you could hook into `wp_head` action. Most theme uses it to load all styles, scripts etc., so you can be sure that you can hook into it. A very basic example would look like this add_action('wp_head', 'bt_custom_head_style'); function bt_custom_head_style () { ?> <style> body { background-color: hsl(200, 50%, 50%); } </style> <?php } This code goes into your `function.php`.
stackexchange-wordpress
{ "answer_score": 0, "question_score": 0, "tags": "theme customizer" }
How to display ACF coustom field from category on author.php I use ACF added a coustom field for category. it works fine in archive.php , here is code: <?php echo get_field('students_no_class', get_queried_object() );?> but it doesn’t work in author.php , nothing show up. in author page I need disaply coustom field value after <?php if (have_posts()) : while (have_posts()) : the_post();?> I also did a test:when I delete author.php, the author page will use archive.php template and the coustom field show up nothing.
In ACF for Authors, you need to supply the author in `'user_'.$user_id` format. Which would be this: echo get_field( 'students_no_class', 'user_'. get_queried_object()->ID ); or this: the_field( 'students_no_class', 'user_'. get_queried_object()->ID );
stackexchange-wordpress
{ "answer_score": 0, "question_score": 0, "tags": "plugins, author" }
Form that generates an ID for the customer I wonder if this is possible on wordpress. In my application I will have a contact form, in this contact form, when filling in the fields, there must be a field that will generate an ID. This ID the customer will be able to write down and save. I will also receive this ID along with the details this person has filled in. It is possible? Or is there already a plugin for this type of situation?
WordPress doesn't provide contact forms by default. So either you'll have to use a form plugin or you'll need custom CODE anyway. Since you didn't provide any CODE or reference to any plugin you're going to use, I cannot provide a sample CODE that'll work for you. In principle, plugins do provide custom hooks that can be used to create the unique ID field for your user. However, make sure you keep that form field disabled and save the value while creating the unique ID (instead of saving after user's form submission), to make sure the ID cannot be altered by the users. For example, if you use Contact form 7 as your form plugin, then there is a plugin called UniqueID for Contact Form 7 that provides similar option. You may check that plugin's code and implement your own. Similar implementation is possible for WP Forms, and I'm sure other form plugins provide similar options as well.
stackexchange-wordpress
{ "answer_score": 1, "question_score": 0, "tags": "plugins, forms, id" }
What is the hook to remove a menu items group from Appearance > Menus column Add menu items I want to remove the Posts menu items group from the Add menu items column in nav-menus.php screen. I tried `unregister_post_type('post');` but found out that built-in types cannot be removed. ![image of nav screen]( **What is the hook to get this done?**
You can use the `register_post_type_args` filter and just set the `show_in_nav_menus` argument to `false`. E.g. add_filter( 'register_post_type_args', 'my_register_post_type_args', 10, 2 ); function my_register_post_type_args( $args, $post_type ) { if ( 'post' === $post_type ) { // or use below to check against two or more post types // if ( in_array( $post_type, array( 'post', 'cpt_1', 'cpt_2', 'etc' ) ) ) { $args['show_in_nav_menus'] = false; } return $args; } And just so you know, for taxonomies (`category`, `post_tag` and custom taxonomies), you would use the `register_taxonomy_args` filter.
stackexchange-wordpress
{ "answer_score": 0, "question_score": 0, "tags": "hooks" }
random post redirect in wordpress with a .php file I saw a website let say `example.com`. Now there is a file called `go.php`. Whenever we go to `example.com/go.php`, we are redirected to a random post on that site. This happens everytime. That site is running Wordpress. Does anyone has an idea of: 1. Where is `go.php` located?? 2. Possible code in `go.php`?
My guess would be that go.php is located in the root of the WordPress install. The code in that fild would be something like this. <?php require 'wp-config.php'; $post = get_posts([ 'post_type' => 'post', 'orderby' => 'rand', 'posts_per_page' => 1, ]); if (!empty($post)) wp_redirect(urldecode(get_permalink($post[0]))); This is a wild guess but it does the job. This code gets one random post. If found post, get the post permalink (url), decode the url (good if you use other languages besides english) and redirect to that post.
stackexchange-wordpress
{ "answer_score": 0, "question_score": 0, "tags": "php, wp redirect" }
How has my Wordpress editor become so basic? Cannot add blocks or see anything visual I'm not sure how but it seems Gutenberg or the block editor has been disabled. I've tried several plugins to re-enable but nothing is doing any different. I only have 1 block showing up on pages (Classic Editor) and cannot add anymore. I cannot find anywhere that will 'enable' the blocks again. Does anyone have any idea what's happened here and how to get it back to default behaviour? ![enter image description here](
Sounds like what I had to deal with recently, having forgotten I had this option checked: ![enter image description here]( on the user profile page. Uncheck it if needed, otherwise it will display the post/page as: ![enter image description here]( with e.g. the add blocks button (+) disabled.
stackexchange-wordpress
{ "answer_score": 1, "question_score": 1, "tags": "block editor" }
Display Visual Composer shortcode if a post belongs in specific categories I have a PHP template file that requires some Visual Composer shortcode to be added. I only want the shortcode to display if a post belongs to certain categories. At any one time, at least three child categories will be chosen for the post. How can I use `echo do_shortcode` to fire only when these categories are selected? What I want is a specific shortcode to be added to the content when the post is in a certain category. Ideally, it will get stripped when the user selects another category that isn't in the series. I'd add it as a div within the template file.
Sounds like you're looking for `has_category()`, which > Checks if the current post has any of given category. You would use it, for example in `single.php`, like so, <?php if ( has_category( array( 'cat-a', 'cat-b', 'cat-c' ) ) ) : ?> <div> <?php echo do_shortcode( 'some_shortcode' ); ?> </div> <?php endif; ?>
stackexchange-wordpress
{ "answer_score": 0, "question_score": 0, "tags": "php, functions, categories, shortcode" }
How many transients is too many transients I am using transients on my Wordpress site, and we may end up with more than 1,000,000 transients in the worst case situation. I think 500,000 is more likely, but I was wondering if having too many transients could cause some performance issues? We keep them for 1 year, because the same requests keep being made throughout the year repeatedly. I know in terms of storage it won't be much of an issue, because a single transient don't take up much space.
It depends if you add an expiration time. If you do not add an expiration time then `autoload` will be yes. This means the option that stores this transient will be loaded on every request even if it's not used. With large numbers of transients this poses an issue purely in terms of memory. I would recommend installing an external object cache if you haven't, as it will make transients both more efficient, and significantly faster ( as well as most of WordPress ). If not, then a dedicated table may be better given the length of time your transients will stick around, but a large number of transients shouldn't cause major issues if they have expiration dates. It may actually be more efficient to implement caching on the API with the expensive endpoints rather than in the consuming WordPress install. You should contact their maintainers.
stackexchange-wordpress
{ "answer_score": 3, "question_score": 0, "tags": "transient" }
Redirect parent taxonomy to it's child I am trying to redirect this url/investments/state/city/ to this url/investments/city/ custom post * investments taxonomy structure: * state 1 * city 1 * city 2 and so on. Any elegant solution?
Assuming `state` and `city` are variable path segments, so you are essentially redirecting `/investments/<one>/<two>/` to `/investments/<two>/` then try the following at the top of your `.htaccess` file: # Redirect "/investments/<one>/<two>/" to "/investments/<two>/" RewriteRule ^(investments)/[^/]+/([^/]+)/$ /$1/$2/ [R=302,L] If you need any further explanation then just ask in comments. **UPDATE:** I've added an end-of-string anchor (`$`) to the end of the `RewriteRule` _pattern_ in the above directive.
stackexchange-wordpress
{ "answer_score": 1, "question_score": 1, "tags": "permalinks, taxonomy, redirect, htaccess" }
How to remove comment count column in Posts inside the admin dashboard? I know how to remove from pages: function remove_pages_count_columns($defaults) { unset($defaults['comments']); return $defaults; } add_filter('manage_pages_columns', 'remove_pages_count_columns'); But can't find the answer how to remove for posts. I have tried: add_filter('manage_posts_columns', 'remove_posts_count_columns'); and add_filter('manage_post_columns', 'remove_post_count_columns'); But none of the above worked. Any help would be appreciated.
Should be work, if you use the filter `manage_posts_columns`. The hook is fine, see < Documentation include examples - < Example: function remove_posts_columns( $columns, 'post' ) { unset( $columns['comments'] ); return $columns; } add_filter( 'manage_posts_columns', 'remove_posts_columns', 10, 2 );
stackexchange-wordpress
{ "answer_score": 2, "question_score": 0, "tags": "functions, wp admin" }
Delete pubished and unpublished posts with wp_delete_post? There is a function that removes all the posts from a given post type but it doesn't remove items that status is "draft". How would it catch the draft items too? function remove_all_kba_data(){ //remove articles $articles = get_posts( array( 'post_type' => 'kb_kba', 'posts_per_page' => -1) ); foreach( $articles as $article ) { //delete post, bypass trash wp_delete_post( $article->ID, true); } }
`get_posts()` can receive an argument describing which post status to operate. I would say something like this: function remove_all_kba_data(){ //remove articles $articles = get_posts( [ 'post_type' => 'kb_kba', 'posts_per_page' => -1, 'post_status' => [ 'published', 'draft' ] ] ); foreach( $articles as $article ) { //delete post, bypass trash wp_delete_post( $article->ID, true); } }
stackexchange-wordpress
{ "answer_score": 3, "question_score": 0, "tags": "posts" }
CPT is simply not displayed in the main archive with "pre_get_posts" I'm trying to get my Custom Post Type to show up in the main archive using pre_get_posts, but it just won't work. However, in the search results the entries are displayed, and they are also displayed within an assigned category. The code I use: function include_custom_post_type_archives($query) { if ((is_category() || is_tag()) && $query->is_archive() && empty($query->query_vars['suppress_filters'])) { $query->set('post_type', array('post', 'landingpages')); } return $query; } add_filter('pre_get_posts', 'include_custom_post_type_archives');
Okay, this is what works for me, thanks to the friendly hint of Jacob Peattie: function include_custom_post_type_archives($query) { if (is_home() && empty($query->query_vars['suppress_filters'])) { $query->set('post_type', array( 'post', 'landingpages', )); return $query; } } add_filter('pre_get_posts', 'include_custom_post_type_archives');
stackexchange-wordpress
{ "answer_score": 1, "question_score": 0, "tags": "custom post types, pre get posts" }
locale filter function running multiple times I'm running the following code: add_filter('locale', 'set_my_locale'); function set_my_locale( $lang ) { $lang = "de"; echo 'test'; return $lang; } This is returning the correct 'de' language, but it is echoing out the 'test' 5 times. Why is it echoing the 'test' 5 times? The reason that I have the echo 'test'; in there is because I want to do some other checks in this function but it seems to run 5 times for some reason.
This is the expected behaviour. The `locale` filter is filtering the result of the `get_locale()` function. All this means is that `get_locale()` is being called at least 5 times.
stackexchange-wordpress
{ "answer_score": 1, "question_score": 0, "tags": "php" }
How to pass a variable into an add_filter() function? I have this code here: $pageLanguage = strtolower($pageMetadata["language"]); $languageArray = array ("afrikaans" => "af", "dutch" => "nl", "french" => "fr", "german" => "de", "spanish" => "es"); $updatedLanguage = $languageArray[$pageLanguage]; add_filter('locale', 'change_my_locale'); function change_my_locale( $locale ) { $locale = $updatedLanguage; return $locale; } I would like to know how to pass the variable $updatedLanguage into the change_my_locale() function please?
You could use an anonymous function and pass the variable to it with `use`. $updatedLanguage = $languageArray[$pageLanguage] ?? ''; if ( $updatedLanguage ) { add_filter('locale', function($locale) use ($updatedLanguage) { return $updatedLanguage; }); } If you're changing the locale at runtime, then you may want to look here Change locale manually at runtime?, where it is noted that the change could have a performance impact. Also, you may need to do the change early enough in the WP loading sequence so that the correct translation file gets loaded - if it something that you need.
stackexchange-wordpress
{ "answer_score": 1, "question_score": 0, "tags": "php" }
WordPress Favicon not Working For Images/Videos/PDFs I am using WordPress with Neve theme, for my site, Favicon is working on posts/pages, but Favicons aren't visible for JPG/PNG/Videos. If I use the Theme Customizer and select the Favicon PNG image, it shows on all posts and images etc. But I want to have different Favicon Images on different URLs. I saw that Theme was adding the below code on my site in Head. <link rel="apple-touch-icon" sizes="72x72" href=" <link rel="icon" type="image/png" sizes="32x32" href=" <link rel="icon" type="image/png" sizes="16x16" href=" this code was inserted `wp_head` to make it work. It works perfectly on my posts and pages. For example the post How Does Elon Musk Manage all his Companies Effectively? the favicon is visible perfectly. But if I Image from the save post The Image shows favicon as WordPress logo instead of my site logo. How to make it WordPress logo programatically.
When opening media files only the file is loaded and not the html head of your file. You can add a 'favicon.ico' file ('.png' may also work – not sure) to your root directory ('public_html/', 'www/' 'domain.com/' depending on server setup) and it should load even for media files as browsers are automaticly looking for an icon there.
stackexchange-wordpress
{ "answer_score": 0, "question_score": 0, "tags": "plugin development, theme development, images, headers, icon" }
Determine if a specific Gutenberg block is used on pages/posts So we have built out a Gutenberg block that is `acf_register_block_type` as the name `pardot-form`. I want to build a widget to basically just display all locations of where that specific block is being used. Is there a way to achieve this and/or are there specific functions from Gutenberg to achieve this? All help is appreciated!
As far as I am aware, there is no built-in way to get all the posts in a site that contain a specific block. Two potential things you could do: 1. You can use the `has_block()` function to determine if a specific post has a specific block. (there is also a more accurate `parse_blocks()` function available). You could loop over all content and fine posts that contain the block that way (probably not great performance wise). 2. Add a custom post meta filed that you toggle to true when a user adds the block to the post and false when the user removes the block. Then you can use a custom WP_Query to get posts where the meta value is `true`. You can use the `useSelect()` React hook to get all the blocks on each post, and check if any have the block you're looking for. Then use a `useEffect()` hook to update the meta.
stackexchange-wordpress
{ "answer_score": 1, "question_score": 1, "tags": "widgets, block editor" }
Load elements without reload page At the outset, I apologize if this is a trivial question, but I have no idea what exactly I'm looking for. I have page with categories like this ![category list]( My goal is when I click on category, page will not reload but will show me elements which are assigned to this category. Each category have one or more elements. Someone can tell me what am I need. Example will be awesome! Best Regards, Bartek
You can do that either by loading all content at page-load but hiding contents till buttons are clicked like in this simple example codepen. Or if you have a lot of content like images that you do not want to load on page-load due to loading speed you could use ajax. But that's complicated for beginners. – Or first option with lazy-loading for the images...
stackexchange-wordpress
{ "answer_score": 0, "question_score": 0, "tags": "themes" }
If post ID has_term? I'm trying to find out whether the post `has_term` by post ID or not. Right now I have this: <?php $postid = $_GET['post_id']; if( has_term( 'campaign', 'type' ) ): ?> //Do something <?php endif; ?> How do I incorporate $postid variable inside the `has_term`? So that I could check only that specific post id. I have tried: <?php $postid = $_GET['post_id']; if( has_term($postid, 'campaign', 'type' ) ): ?> The above doesn't work. Need help, thanks.
The 3rd parameter of `has_term()` accepts a WP_Post or Post ID. Docs on `has_term()`. In your example code, it would look like this: <?php $postid = $_GET['post_id']; if( has_term( 'campaign', 'type', $postid ) ): ?> //Do something <?php endif; ?> Where `campaign` would be the term, `type` would be the taxonomy, and `$postid` is the post that may have the `campaign` term.
stackexchange-wordpress
{ "answer_score": 1, "question_score": 1, "tags": "php" }
Why does a <button> on Comment edit page submit the page? I followed this guide to add a "copy to clipboard" button on the edit Comment page (comment.php?action=editcomment) It works but it also submits the page (i.e. the page reloads back to the comments list) but I don't understand why. This is the html: `<input type="hidden" value="This is copied" id="civicrm-subject-code-field"><button class="ed_button button button-small" onclick="copy_civicrm_subject_code()">Copy</button>` This is the JS: async function copy_civicrm_subject_code() { /* Get the text field */ var copyText = document.getElementById("civicrm-subject-code-field"); /* Select the text field */ copyText.select(); /* Copy the text inside the text field */ await navigator.clipboard.writeText(copyText.value); }
This is happening because the entire comment edit page is inside a `<form>` element, and the `<button>` element submits any form that it belongs to. This is the normal behaviour of buttons in HTML. If you don't want a button to act as a submit button, you need to set the `type` attribute to `button`: <button class="ed_button button button-small" onclick="copy_civicrm_subject_code()" type="button"> Copy </button> The default `type` attribute for a button is `submit`, which is why it behaves that way unless you set it to `button`.
stackexchange-wordpress
{ "answer_score": 1, "question_score": 0, "tags": "javascript, comments, forms" }
Echo the number of users using WP_User_Query? Ok, so right now I can easily echo the number of posts that has a specific `meta_key` and `meta_value`: $query = new WP_Query( array( 'meta_key' => 'usp-custom-1', 'meta_value' => get_permalink() ) ); echo $query->found_posts; I'm trying to do something similar except for echoing the number of users that has a specific user_meta data. I'm trying this: $query = new WP_User_Query( array( 'meta_key' => 'cash_out_status', 'meta_value' => 'pending' ) ); echo $query->found_users; But the above doesn't display anything. I guess I'm making a mistake somewhere in the code. Any help would be greatly appreciated. Thanks.
We have the public properties: WP_Query->found_posts WP_Comment_Query->found_comments WP_Network_Query->found_networks WP_Site_Query->found_sites but then comes this private property (that's also made public via magic getter): WP_User_Query::$total_users but not `found_users` as expected, so the confusion is natural :-) Look into the public `get_total()` method and the `count_total` bool attribute (true by default) in the docs.
stackexchange-wordpress
{ "answer_score": 1, "question_score": 2, "tags": "wp user query" }
How To Read Read Custom Post Type Data in Headless CMS Mode I'm doing my site with two pieces -- the headless CMS on a subdomain where content is entered, and the root domain where I display data. Only WP is installed in the subdomain, not the root domain. In the subdomain, I created a custom post type called Staff, and then items inside are a Member. I noticed that I can't use the URL... < (WP REST API) ...to read these items. Looking in the docs, I see that I can address it as... < When I use /staff, it shows me the core post fields, but not any of the custom field groups. (Note, I'm using the Custom Post Types plugin from TotalPress.org.) How do I get a given staff member's custom field properties on their record? I can access someone such as: < ...but there are no custom fields in there that I attached to this record. How do I use the REST API to get the custom fields attached to a custom post type?
I found the fix without code. I installed the Rest API Helper Plugin and it now exposed the custom fields on a given post type.
stackexchange-wordpress
{ "answer_score": 0, "question_score": 0, "tags": "custom post types, custom field, rest api" }
Combining wp_list_authors with get_user_meta i am using the wp_list_authors function as the following: <?php wp_list_authors( array( 'show_fullname' => 'true', 'orderby' => 'display_name', 'order' => 'ASC' )) ?> However this shows the authors by **firstname + lastname** I want to switch that so it shows the users **lastname + firstname**. I cant figure out how can i use the **get_user_meta** in the function. It is possible or should I use something else than wp_list_authors?
What you want is not supported by `wp_list_authors()`. To output them the way you want you will need to use `get_users()` and display them yourself. $authors = get_users( array( 'orderby' => 'display_name', 'order' => 'ASC' ) ); foreach ( $authors as $author ) { echo esc_html( $author->last_name . ' ' . $author->first_name ); } You can wrap the output in elements as needed, and pass `$author->ID` to `get_user_meta()` if you need any metadata. You can get a link to the author archive using `get_author_posts_url()`.
stackexchange-wordpress
{ "answer_score": 1, "question_score": 0, "tags": "user meta, list authors" }
Oxygen builder custom Elements Is there any tutorial or documentation to create elements in oxygen builder? I want to create my own element to show in oxygen builder. Any help link or video?
There is no proper documentation of the Oxygen Elements API so far. But they released a pretty good video about it recently: <
stackexchange-wordpress
{ "answer_score": 0, "question_score": 1, "tags": "customization" }
How to say if meta_value is greater than 0 in an array? Right now I have this: $args = array( 'meta_key' => 'userfunds', 'meta_value' => '0', ); Basically this will show users who have exactly '0' as `meta_value`. How do I say that `meta_value` has to be greater than '0'? I have tried: 'meta_value' > '0', But using the above, it shows all users, regardless of their value. So I guess using `>` in the array is an invalid line and not what I need. I know I'm probably missing something very small in my code? should I use `compare`? Any help would be appreciated.
As documented, you can use `meta_compare`: $args = array( 'meta_key' => 'userfunds', 'meta_value_num' => '0', 'meta_compare' => '>', ); Note that I changed `meta_value` to `meta_value_num`. This ensures the values is treated as a number for the comparison. You'd probably be ok without it, but it doesn't hurt.
stackexchange-wordpress
{ "answer_score": 1, "question_score": 0, "tags": "php, array" }
Compare two meta key values against each other inside the get_posts array? I'm banging my head to the wall all day trying to figure this out. I have two meta keys a1 and a2 with numbers inside. I'm trying to show posts that are a2 > a1. In a nutshell, here's what I'm trying to accomplish: $posts = get_posts(array( 'post_type' => 'post', 'meta_query' => array( //return both meta keys array( 'key' => 'a1', ), array( 'key' => 'a2', ), //only show posts that a2 meta_value is greater than a1 meta_value 'a2' > 'a1' ), )); I know it should be possible to do this somehow. I'm not the only one in the world trying to compare whether one post's meta_key value is greater than other... Desperately need help or any kind of solution.
You can't do this in the meta query I'm afraid. You'd need to get _all_ the relevant records in meta query, then make that comparison inside PHP, to filter out the records you don't need.
stackexchange-wordpress
{ "answer_score": 2, "question_score": 0, "tags": "php, post meta, array" }
remove edit link only for published post and pending post Currently i m using this shorocdes add_filter( 'post_row_actions', 'remove_row_actions', 10, 1 ); function remove_row_actions( $actions ) { if( get_post_type() === 'post' ) unset( $actions['edit'] ); return $actions; } for removing edit link from published post but this code is applied on all post states and i want to apply this filter only for published and pending post. can any one help me to apply this filter only for published and pending post instead of All posts ![enter image description here](
Try this, where I changed the function to accept the second parameter which is the current post in the list table: add_filter( 'post_row_actions', 'remove_row_actions', 10, 2 ); function remove_row_actions( $actions, $post ) { if ( $post && 'post' === $post->post_type && in_array( $post->post_status, array( 'publish', 'pending' ) ) ) { unset( $actions['edit'] ); } return $actions; }
stackexchange-wordpress
{ "answer_score": 0, "question_score": 0, "tags": "functions, code" }
get_current_screen() return null I want to put JavaScript code on certain pages in frontend. But the output return null . add_action( 'wp_footer', function () { $screen = get_current_screen(); var_dump( $screen ); }, 999 );
`get_current_screen` is an Admin API, it can't be used on the frontend, only in `/wp-admin` screens. If you want to run javascript code only on certain pages, either enqueue it on those pages, or load it on all pages and check the body classes, or many other methods. `get_current_screen` is not the way to do it.
stackexchange-wordpress
{ "answer_score": 1, "question_score": 1, "tags": "plugin development, functions, filters, hooks" }
Wordpress remove_filter not working The site date has changed from Gregorian date to Jalali with a plugin, and that's good. if (get_locale() == 'fa_IR') { add_filter('wp_date', 'wpp_fix_i18n', 10, 4); } And now I want the date of the site to change to Jalali only when the language of the site is Persian (fa_IR). And I added this code but it does not work. if (get_locale() != 'fa_IR') { remove_filter('wp_date', 'wpp_fix_i18n', 10, 4); }
The "remove_filter" function only accepts 3 params: the hook name ("wp_date"), the callback function ("wpp_fix_i18n") and the priority (10). You are using 4 params. I'm sure your problem is related with the execution lifecycle. You are trying to remove a filter before it was created. To solve it, wrap your function inside init hook in your theme functions.php to ensure plugin is loaded (and filter is added): function mytheme_fix_date_issue () { if (get_locale() != 'fa_IR') { remove_filter('wp_date', 'wpp_fix_i18n', 10); } } add_action('init', 'mytheme_fix_date_issue');
stackexchange-wordpress
{ "answer_score": 0, "question_score": 0, "tags": "filters" }
Determining when was the last time a plugin was activated I'm currently doing an audit on a WordPress site for some supervisors and was curious if there was any way under the hood to see when was the last time a plugin was actually activated. This will give me some leverage in removing them if its been a while. Is there anyway I can complete this type of investigation through WordPress?
It looks like, in a Multisite installation, any network-wide plugins record their activation time in a site option. By default, plugins activated in a single site in a Multisite network (or in a single-site installation) do not. See the source of the `activate_plugin()` function. You _could_ write a simple plugin that records that information, using the `activated_plugin` hook, but that won't help you with any older plugins -- any data you record that way would only exist from now[^1] on out. [^1]: If by "now" we mean "the moment you activate your plugin-tracking plugin".
stackexchange-wordpress
{ "answer_score": 2, "question_score": 0, "tags": "plugins" }
Woocommerce template file outputting <strong><code> tags I'm struggling with the editing of the woocommerce template files. In particular, I'm trying to create a custom cart page and, as guidelines, I've copied the cart.php template file to my template folder. However, any html that I write gets enclosed in <strong><code></code></strong> tags. I really don't understand why, does anybody have an idea? Here's an example: <?php defined( 'ABSPATH' ) || exit; do_action( 'woocommerce_before_cart' ); ?> <div><span>hello</span></div> It outputs <strong><code><div><span>hello</span></div></code></strong>
Cart page is loaded via customizable WordPress Page. Edit your page and check if the "HTML" editor tab content contains any "code" HTML tag. If you cannot find this tag, you will need to check all actions executed with "woocommerce_before_cart" and "woocommerce_after_cart".
stackexchange-wordpress
{ "answer_score": 0, "question_score": 0, "tags": "php, customization, code" }
Wordpress basic functions show on top in custom shortcode I created a function in my functions.php to show related posts for a custom posttype. Because the original developer used a themebuilder, I need to use a shortcode to display this function on the front-end. A part of the code I use is if($related_cats_post->have_posts()): while($related_cats_post->have_posts()): $related_cats_post->the_post(); $postsList .= '<li><a href="' . the_permalink() . '">' . the_title() . '</a></li>'; endwhile; return '<ul>' . $postsList . '</ul>'; It gets the job almost done. The only problem is that because I use the_permalink() and the_title(), the link and the title shows up on top of the page and not in the unordered list as they supposed to do. I don't know why this happens and how to fix this. Is it maybe because I call the function within a shortcode? Is there a way to fix this?
You need to use the equivalent functions that return their value. Those are `get_the_permalink()` and `get_the_title()`. Most WordPress template functions that begin with `the_` and echo their values have equivalent functions that return their values that begin with `get_the_`,
stackexchange-wordpress
{ "answer_score": 3, "question_score": 0, "tags": "permalinks, shortcode" }
'orderby' => 'rand' alternative for better performance? I have been told that using this in the array: 'orderby' => 'rand' will cause this: > Ordering by random is extremely expensive to query, involving creating temporary database tables, and scans, as it has to copy the entire posts table, then randomly re-order the posts, then finally do the actual query on the new table before destroying it. And I have been advised: > It's much easier to ask for the first post that occurs after a random date. Can anyone elaborate on this? Is there an array code line that will do the above? Any resource regarding this would be very appreciated.
If something needs to be "random" than the last post ( or the one before last ) will answer that definition well enough. Just because you know it is not a post generated by a randomizing algorithm do not mean it is not random to the user. There is just no way to have a "truely" random post if you care about performance, and that is before even discussing page caching.
stackexchange-wordpress
{ "answer_score": 1, "question_score": 1, "tags": "php, array" }
the_date() and the_time() functions display actual date an time instead of published date and time It's really hilarious but my `the_date()` and `the_time()` functions show the current date and time instead of the post's publication time, therefore at each refresh of the page, the time changes according to the actual time and date. I am using these functions in a single template for a custom post in the loop, like so: <?php if(have_posts()): ?> <?php while(have_posts()): the_post(); ?> <h3> <?="Titre du projet"?> </h3> <?php the_title(); ?> <h3><?="Description"?></h3> <?php the_content(); ?> <p> <?php the_date(); ?> à <?php the_time(); ?> <?php endwhile?> <?php endif;?> What's wrong? I tried other similar functions or get post date in the `$post` object, but in their format, the date and time are inseparable. and I need them separately. Thanks.
So, this is what I finally think: `the_date()` and `the_time()` purpose is to display published date and time, even if in the documentation they said they display or retrieve the date/time the current post was written. my error comes from the fact that I expected to have the date of writing (draft) in the absence of the date of publication; And unfortunately all my posts were drafts, so I'm guessing that because the posts weren't published, the functions return the current date/time. And as soon as they were published, the date & time have stopped to the time they have been published.
stackexchange-wordpress
{ "answer_score": 0, "question_score": 0, "tags": "functions, loop, templates" }
array of meta values using WP_User_Query I don't see that it is possible when I look at the WordPress documentation but I wanted to confirm. I want to check multiple meta values against one meta key eg: $user_query = new WP_User_Query( array( 'meta_key' => 'user_charname', 'meta_value' => 'squarepants', 'orderby' => 'meta_value_num', 'order' => 'DESC' )); I was hoping I could just use `'meta_value' => array('value1', 'value2')` but that does not work. I have tried this as pointed out by Jacob (modified) but it gives me what appears to be all results and isn't working as intended. $args = array( 'meta_query' => array( array( 'key' => 'user_charname', 'value' => array('spongebob', 'mickey'), 'compare' => '=' ) ) ); $user_query = new WP_User_Query( $args );
If you just wanted to know if it's possible, then yes **it is possible**. But the problem as I could see it from your edited question, is that you set the `compare` to `=` which should instead be `IN`. However, you didn't actually have to set it because when you supply an array of values, the operator will default to `IN`. So the correct code would be: 'meta_query' => array( array( 'key' => 'user_charname', 'value' => array('spongebob', 'mickey'), 'compare' => 'IN' // use IN ) )
stackexchange-wordpress
{ "answer_score": 1, "question_score": 0, "tags": "wp query, wp user query" }
Permalinks migration issue I have a blogging website with over 5000 blogs, with decent traffic and backlinks from the top places. Right now, the permalinks look like this domain .com/blog-post Which I want to switch to domain .com/category/blog-post But, If I am changing the permalinks from the settings, all the old backlinks are showing 404, which means it can hurt the SEO real bad. Let me know how to make the old domain .com/blog-post automatically redirected to the new domain .com/category/blog-post permalink?
After days of tweaking and trying out a new thing, I found a WordPress plugin, which auto redirected all my links to the ones similar to the value set in Dashboard > Settings > Permalinks. The second solution is to connect your website to Jetpack, and it also solves this problem. If you do not want to go with Jetpack, since it takes many resources, I would suggest going with the first option.
stackexchange-wordpress
{ "answer_score": 0, "question_score": 0, "tags": "permalinks" }
Wp Cron and Wordpress Updates If I disable wp-cron from config, will automatic updates still work? In one of my sites I need to disable wp-cron as its causing high CPU usage but of course I wouldn't want to disable automatic updates. Any suggestions (such as using a crontab/cronjob) would be apprecaited.
> If I disable wp-cron from config, will automatic updates still work? No, neither will scheduled posts, transient cleanup, trash clearing after 30 days, or automatic plugin updates, and some other things. Anything that relies on timed or scheduled activities will break. It seems you already know the solution, though the real solution is to identify which cron jobs are using so much CPU and fix those. Changing how cron runs from WP Cron to a crontab will give limited relief.
stackexchange-wordpress
{ "answer_score": 2, "question_score": 0, "tags": "wp cron" }
Can I write 'RewriteCond' using 'functions.php'? I want to add 'rewrite condition' in **.htcaccess** but unfortunately I don't have access of that. Can I write conditions in functions.php ? If yes, how to achieve that ? I want to add these lines: RewriteCond %{QUERY_STRING} ^.{1000,}$ RewriteRule ^wp-admin/load-scripts\.php$ - [F]
use this < if you are not willing to use any plugin, understand the code and implement in functions.php or your own custom plugin. cheers.
stackexchange-wordpress
{ "answer_score": 1, "question_score": 1, "tags": "php, functions, rewrite rules, security, mod rewrite" }
Change Header Image on Blog Post for Mobile View I need to use a different header image for a specific blog post. < I have tried different CSS variations, but to no avail. @media (max-width: 767px) { .post-id-41012 .page-banner bg { background-image: url(' !important; } } Thank you in advance for any suggestions.
You're not calling the class correctly. The container has both the `page-banner` and the `bg` classes, so you should write it like this: `.page-banner.bg` And the class `post-id-41012` doesn't exist in your document. `postid-41012` does. So try this way: @media (max-width: 767px) { .postid-41012 .page-banner.bg { background-image: url(' !important; } }
stackexchange-wordpress
{ "answer_score": 1, "question_score": 0, "tags": "css, blog, mobile, responsive" }
What is the meta field in the response of the user REST API? I use this command to send to the API: curl -X 'GET' \ ' \ -H 'accept: application/json' \ -H 'authorization: Basic SmVmZnJleTpCdW1ibGViZWUwNjA0' and I get this response: { "id": 14, "name": "User", "url": "", "description": "", "link": " "slug": "User", "avatar_urls": { "24": " "48": " "96": " }, "meta": [], "_links": { "self": [ { "href": " } ], "collection": [ { "href": " } ] } } Does anyone know what the "Meta":[] field is? If it is the user's Metadata then how do I use this?
Look into register_rest_field() to register meta with the rest api. add_action( 'rest_api_init', 'adding_user_meta_rest' ); function adding_user_meta_rest() { register_rest_field( 'user', 'collapsed_widgets', array( 'get_callback' => 'user_meta_callback', 'update_callback' => null, 'schema' => null, ) ); } And then put your get_user_meta bit in the callback. function user_meta_callback( $user, $field_name, $request) { return get_user_meta( $user[ 'id' ], $field_name, true ); } The WP_REST_Meta_Fields class may provide more useful insight as well. Answer copy from - Getting user meta data from WP REST API
stackexchange-wordpress
{ "answer_score": 0, "question_score": 1, "tags": "rest api" }
adding class to excerpt I want to add different classes to some excerpts.when wrap the excerpt with it doesn't work.how can I add my class to excerpt? <?php <p class="myclass"><?php the_excerpt(); ?></p> output: <p class="myclass"></p><p>excerpt text</p>
`the_excerpt()` function bascially echo(es) the `get_the_excerpt()` function output, which in turns wraps the `$post->post_excerpt` value in html `<p>` tags. So you can either strip the html markup, <p class="myclass"><?= wp_strip_all_tags( get_the_excerpt(), true ) ?></p> or, if you have access to the `$post` object simply, <p class="myclass"><?= $post->post_excerpt ?></p>
stackexchange-wordpress
{ "answer_score": 1, "question_score": 0, "tags": "theme development, excerpt" }
How to declare a variable in a loop and make it available in the template file I was faced with a minor issue but can't solve it myself. I need to add the value on the variable after all loop iterations. And nothing problem, but I need to use this variable in the other file. for example: while( have_posts() ) { the_post(); $x = ''; $x++; get_template_part( 'content', 'right' ); } Now I need to get the $x value with iteration in content-right.php I try to declare a variable into this file but in this case no iteration. Is there any way to solve this?
You are re-initializing your `$x` variable on every iteration of the loop. Maybe you want to move its initialization outside the loop? To get `$x` variable value in the `content-right.php` file you can declare it as global: global $x; $x = 0; while( have_posts() ) { the_post(); $x++; get_template_part( 'content', 'right' ); } Then you can use it in the `content-right.php` file: global $x; # ... here you can use $x variable value
stackexchange-wordpress
{ "answer_score": 0, "question_score": 0, "tags": "loop, get template part" }
Can I use WooCommerce in a headless CMS setup? I don't have a question about coding in WordPress, but I was just wondering if I have a headless CMS setup, can I still have ecommerce functionality with WooCommerce?
Yes. WooCommerce has endpoints and you can access them with the standard WordPress REST API. /wp-json/wc/v3/products /wp-json/wc/v3/products/<id> Did a little search and found that they have documentation available here: <
stackexchange-wordpress
{ "answer_score": 2, "question_score": 0, "tags": "theme development, headless" }
Where are the admin notifications stored? I'm looking to add some custom functionality to the admin side and I want to change the way the admin notifications work. Where are the admin notifications stored? And when a user dismisses one, where is that being recorded?
> Where are the admin notifications stored? **They aren't.** Admin notices have no storage unless you implement it yourself for your plugin/theme. WordPress provides hooks and styling for displaying admin notices, but that's it. It might provide styling for dismissible admin notices but it provides no storage or registration mechanisms for persistence. > And when a user dismisses one, where is that being recorded? **It isn't** , native WP admin notices don't provide this, it's implemented by the plugin/theme author. They might store this in a cookie, local storage, user meta, etc, you would need to ask each plugin/theme vendor individually. There is currently no general mechanism. * * * As an aside, there is a feature plugin for creating a notification centre in core, but at the time of writing it has not been merged, and its status is uncertain. You should give it a look.
stackexchange-wordpress
{ "answer_score": 2, "question_score": 1, "tags": "wp admin, notifications" }
Create an array with all the links of the years' archive (of a custom post type) I have a custom post type called "papers" and I need to create an array with all the archive links per year that exists. Something like: array ( [0]=> ' [1]=> ' cause there's no post in 2020 [2]=> ' ) I know it's weird but I'm going to feed a chart js with it.
I just recieved this answer in the StackOF page and it worked, though I don't fully understand it. $links = wp_get_archives(array('echo'=>'0','format'=>'<link>')); $regex = '/\b(https?|ftp|file):\/\/[-A-Z0-9+&@#\/%?=~_|$!:,.;]*[A-Z0-9+&@#\/%=~_|$]/i'; preg_match_all($regex, $links, $matches); $array_links = $matches[0]; print_r($array_links); Just added `'post_type' => 'myCPT'` in the `wp_get_archives()` array and it worked. Get to the real answer: <
stackexchange-wordpress
{ "answer_score": 0, "question_score": 0, "tags": "php, array, custom post type archives" }
WP Cli will not execute on Windows I have tried to install Wordpress CLI on my windows machine running windows 10. But for some reason everytime i try to run the wp Command it says 'sh' is not recognized as an internal or external command,operable program or batch file. I have tried multiple times to reinstall it and set it up from scratch with different guides but it just won't work. This is what the bat file says @ECHO OFF SET BIN_TARGET=%~dp0/./wp-cli.phar php "%BIN_TARGET%" %* This is the environment variable i am using to point it to the bat file ![enter image description here]( That is where the .phar file and my .bat file are located to run the CLI. All help is appreciated Regards Jonas Bang
Currently i have several process running in my CI/CD with wp-cli and all works fine in windows and unix. In my experience this is your best option in windows: **#1** Add PHP to your Windows Path Variable **#2** Install, as @Rup suggests, Git-bash terminal. **#3** Execute an wp-cli command like that: vendor/bin/wp cache flush --path=public/wp-cms/wp-core _*This code consider you are using wp-cli managed withcomposer, and the files are locatted at vendor folder, otherwise you can replace `vendor/bin/wp` with `wp`_ ![enter image description here](
stackexchange-wordpress
{ "answer_score": 1, "question_score": 1, "tags": "wp cli, windows, command line" }
Is there any solution, ide/tool etc., for automatic escaping for WordPress? Is there any tool/ide etc. to escape WordPress theme/plugin files automatically? How can I do it with PhpStorm?
A tool like PHP CodeSniffer, combined with the WordPress Coding Standards can be used to warn you if values are not being escaped. These warnings can be shown in the editor if the editor has a PHPCS extension of some kind (VS Code does, but I'm not sure about PhpStorm). With PHPCS it's possible to automatically fix many issues using `phpcbf`, but I don't think the escaping rule is one of them. This is because the proper escaping function to use depends entirely on context, and an automated tool won't necessarily know which is appropriate. It would only know if one wasn't used. Frankly, you'd be much better of learning the purpose of the various escaping functions and getting in the habit of using them, rather than relying on automated tools to secure your code.
stackexchange-wordpress
{ "answer_score": 1, "question_score": 0, "tags": "theme development, escaping" }
Why is a renamed custom template file still showing up in the template dropdown menu? I recently renamed a custom template file, changing it from `template-programs.php` to `template-program-schedule.php`. In my template dropdown menu, Program Schedule shows up as expected, but Programs is also still there. I have cleared all caches and hard refreshed the browser, but it still shows up. I've tested the template dropdown functionality by creating dummy template files, which always appear in the dropdown menu after creation and then disappear as expected when deleted, but Programs remains in the list. I searched throughout the whole website directory, and there is no `template-programs.php` file anywhere. Can a template listing be generated by a plugin or some other means without there being a respective template file? How can I remove this template dropdown listing and/or track its source? Or, is it possible to flush and rebuild the template dropdown menu?
Scan the files for a comment header that might have `Template Name: Programs` present. The template drop-down is populated by the comment header in files. I believe this is only true for files in the theme's root folder and from a `template` sub-folder within the theme (if one exists).
stackexchange-wordpress
{ "answer_score": 1, "question_score": 0, "tags": "page template, page attributes" }
How to add the sidebar to all the pages except the home page? I am creating a theme and I need some idea to create a below structure on my all the page except on the home page. ![enter image description here]( I know how to create a menu, sidebar, footer, and call dynamically on the page. My issue is, In which file do I have to edit it in my theme so that it will not affect on the home page.
I don't know if I understand you correctly, but probably in the file which calls `get_sidebar()`: You could do something like if ( ! is_home() ) { get_sidebar(); } Or in your header.php where the main-element starts (which probably wraps the sidebar). You could give it a class if the page is not the home page: <!-- body and header-stuff --> <main class="<?php echo is_home() ? 'home-without-sidebar' : 'with-sidebar'; ?>"> <!-- other stuff --> <?php if ( ! is_home() ) { get_sidebar(); } ?> And then define CSS accordingly: .home-without-sidebar { /* whatever properties */ } .with-sidebar { display: grid; grid-template-columns: 20rem 1fr; /* more properties here */ }
stackexchange-wordpress
{ "answer_score": 1, "question_score": 0, "tags": "php, plugin development, theme development, themes, html5" }
Retriving all users with REST API not working At the moment I'm using Postman to hit the endpoints and I have a successful Basic Authentication but so far I'm unable to get all the registered users. My request: returns only users that have posts even though I have inserted: add_filter( 'rest_user_query' , 'custom_rest_user_query' ); function custom_rest_user_query( $prepared_args, $request = null ) { unset($prepared_args['has_published_posts']); return $prepared_args; } in my functions file. I have also tried applying a filter: But I still get the same result: Only users with posts. I have been banging my head on for days now...
**The problem may be pagination** The API only returns 10 results per page, and needs follow up requests to fetch the rest. WP includes a HTTP header that tells you how many total results and the number of pages. It has a hard limit of 100 per page maximum, if you request 200, you will be capped to 100. So your missing users may be on page 2 or 3 etc I strongly recommend reading the REST API handbook on the official developer site, here is the page detailing pagination: <
stackexchange-wordpress
{ "answer_score": 1, "question_score": 0, "tags": "rest api" }
How can I show "sold out" instead of "out of stock" for some products with particular tags and categories hello comrades How can I show **sold out** instead of **out of stock** for some products with particular tags and categories. add_action( 'woocommerce_before_shop_loop_item_title', function() { global $product; if ( !$product->is_in_stock() ) { echo '<span class="now_sold_list">out of stock</span>'; } }); add_action( 'woocommerce_before_single_product_summary', function() { global $product; if ( !$product->is_in_stock() ) { echo '<span class="now_sold_single">out of stock</span>'; });
**Try this** add_filter( 'woocommerce_get_availability', 'change_out_of_stock_text_woocommerce', 1, 2); function change_out_of_stock_text_woocommerce( $availability, $product_to_check ) { if ( ! $product_to_check->is_in_stock() || has_term( 'my-ex-cat-slug', 'product_cat' ) || has_term( 'my-ex-tag-slug', 'product_tag' )) { $availability['availability'] = __('Sold Out', 'woocommerce'); } return $availability; } Change `my-ex-cat-slug` with your Category's slug and `my-ex-tag-slug` with tag's slug
stackexchange-wordpress
{ "answer_score": 0, "question_score": 0, "tags": "woocommerce offtopic" }
Woocommerce disable order item link (backend) I'm facing a problem where I couldn't disable the order item link for the backend (user role: shop manager). I've found some solutions but only tackle to the front end (customer-order page). However, I added a code to functions.php to target only on shop_order order item link add_filter( 'woocommerce_order_items_shop_order', '__return_false' ); But it doesn't work. Does this require adding javascript in order to disable the order item link on the backend? Been struggling with this for a long time. ![enter image description here](
You can do using this way - This template can be overridden by copying it to yourtheme/woocommerce/emails/plain/email-order-details.php if ( $sent_to_admin ) { /* translators: %s: Order link. */ echo "\n" . sprintf( esc_html__( 'View order: %s', 'woocommerce' ), esc_url( $order->get_edit_order_url() ) ) . "\n"; }
stackexchange-wordpress
{ "answer_score": 0, "question_score": 0, "tags": "php, woocommerce offtopic, javascript" }
Category title output before opening title tag I am using this code to add the category title to the category archive titles: function filter_events_title( $title ) { // Single venues if ( tribe_is_venue() ) { $title = sprintf('%1$s Running Race Calendar', get_the_title() ); } // Category pages elseif ( tribe_is_upcoming() && is_tax() ) { $title = sprintf('%1$s Race Calendar', single_cat_title() ); } return $title; } add_filter( 'tribe_events_title_tag', 'filter_events_title' ); While the category title is being output, it is BEFORE the opening tag. How can this be fixed so it is within the tags? Here's the source code: 5K <title> Race Calendar &#8211; Running World</title>
You can fix that by setting the second parameter for `single_cat_title()` to `false`, which then returns the title instead of echoing it (before the `<title>` tag), like so: $title = sprintf('%1$s Race Calendar', single_cat_title( '', false ) );
stackexchange-wordpress
{ "answer_score": 2, "question_score": 0, "tags": "php, categories, taxonomy, seo" }
WordPress Multisite (sub-directory based), change subsite URL I have a WordPress Multi-site, sub-directory based like this: < I have a site within the multisite < that I want to rename to < How would I do this? I'm assuming besides running a search and replace tool/plugin, I would need to update the URL of that site (i.e., < in the database somewhere?
If you go to your Network Admin -> Sites menu, you should be able to edit the site and change the site's **Site Address (URL)** to whatever you need it to be. As for the search/replace: I recommend using WP-CLI's `search-replace` command to do this, if you've got it available. `wp search-replace --url= --dry-run` to see what will be replaced, and then run it again without the `--dry-run` argument to actually _do_ the search/replace.
stackexchange-wordpress
{ "answer_score": 1, "question_score": 0, "tags": "multisite" }
Filter 'comment_notification_text' not working I am wanting to edit the content that is sent to admins in the comment moderation email notification. I have looked at multiple places and they all seem to give roughly the same example to achieve this, but it isn't working for me. I am adding this to my functions.php file: add_filter('comment_notification_text', 'my_comment_notification_text', 10, 2); function my_comment_notification_text($notify_message, $comment_id) { return $notify_message . ' This is some extra text that I want to add'; } The additional text isn't being added to the notification. What am I doing wrong?
Try using this hook instead: `comment_moderation_text`. The args are the same.
stackexchange-wordpress
{ "answer_score": 0, "question_score": 0, "tags": "php, filters" }