INSTRUCTION
stringlengths 11
999
| RESPONSE
stringlengths 0
999
| SOURCE
stringlengths 16
38
| METADATA
dict |
---|---|---|---|
how to block direct access to multiple thank you pages?
I have multiple contact forms in my wordpress website and have a different thankyou page for each. So, i want to prevent direct access of thankyou pages by just entering urls. I want if the user fills the form than it is only redirected to that forms thankyou page.
I have working code for 1 thankyou page but i don't know how to set up for multiple contact forms & thankyou pages.
// ID of the thank you page
if ( ! is_page(1911)) {
return;
}
// coming from the form, so all is fine
if (wp_get_referer() == ' {
return;
}
// we are on thank you page
// visitor is not coming from form
// so redirect to home
wp_redirect( get_home_url() );
exit;
} );```
Other thankyou page id's: 1269, 1825, 1623
Other contact form page urls: | I have solved the issue by myself. I am posting the solution here in case if someone gets the same problem.
function wpse15677455_redirect() {
$ref = wp_get_referer();
if (is_page(1911) && $ref !== "
wp_redirect( get_home_url() );
}
else if(is_page(1269) && $ref !== "
wp_redirect( get_home_url() );
}
else if(is_page(1825) && $ref !== "
wp_redirect( get_home_url() );
}
else if(is_page(1623) && $ref !== "
wp_redirect( get_home_url() ); exit();
}; | stackexchange-wordpress | {
"answer_score": 1,
"question_score": 1,
"tags": "wp redirect, template redirect"
} |
admin-ajax return error 400 for Chrome/Edge but not Firefox
I have a bug with an Ajax request but it works on Firefox. You can test it clicking here
For Edge/Chrome I got a 400 error.
In Edge I got this error :
> HTTP400: INCORRECT REQUEST - the request could not be processed by the server due to invalid syntax.
What could be the problem in my request ?
Request : `
Why it works for Firefox but not for others browsers ? | Problem fixed ! The problem was not due to a browser matter. `wp_ajax_nopriv_myfunction` was wrapped by `is_admin()`. That could not work. I was logged in in Firefox and not in Chrome that´s why I thought it was a browser matter. | stackexchange-wordpress | {
"answer_score": 3,
"question_score": 1,
"tags": "ajax, browser compatibility"
} |
Can I change the Wordpress default color?
I just installed Wordpress and am struggling to change the default color. Currently, my default color is "pink" because I have the Wordpress 2020 theme. However, I would like to change it to black.
I'm mainly interested in chaning the colors of my menu navigation.
When clicking on the color customization menu, I have the option to select between Default and Custom.For some reason, I cannot pick black as a custom color.
Any tips on how to change my default color?

In the Additional CSS you'll have a text area where you can put your own CSS, use this:
body:not(.overlay-header) .primary-menu > li > a, body:not(.overlay-header) .primary-menu > li > .icon, .modal-menu a, .footer-menu a, .footer-widgets a, #site-footer .wp-block-button.is-style-outline, .wp-block-pullquote:before, .singular:not(.overlay-header) .entry-header a, .archive-header a, .header-footer-group .color-accent, .header-footer-group .color-accent-hover:hover{
color:#000;
}
That'll set all of the menu items that are currently pink to be black.

I updated some plugins and few minutes later when i check my site i see white screen.
What i tried:
I reboot server I loaded a backup from what i before I change the name of plugins directory to plugins2 I added debug true in wp-config.php
Stil only white screen.
Please help this is urgent. | Check your emails: a white screen should make Wordpress send you an email saying there’s a critical problem and inviting you to fix it.
Could caching be stopping wp_debug from working yet? (Clear cache)
If renaming plugins folder doesn’t work, try moving the current theme directory out of the /themes folder. Ensure the /twentytwenty theme is in the /themes folder so that it defaults to that.
Do you have a backup of the database? | stackexchange-wordpress | {
"answer_score": 2,
"question_score": -1,
"tags": "plugins"
} |
Cannot get custom javascript to execute on page
I have a simple piece of "hello world" code I'm trying to execute on a page. I'm adding it using a PHP snippet:
add_action( 'wp_head', function () { ?>
<script type="text/javascript" src="
jQuery(document).ready(() => {
jQuery('div#tm-extra-product-options').click(() => {
console.log("it's working!")
});
});
</script>
<?php } );
I can get it to show up in the page source and if I paste that directly into the console it works fine, however when I load the page and try it, I get nothing. I know that jQuery is loading because it is defined in the console without my intervention (previously this was not the case), however the code itself appears to not work at all. | Try this.
add_action ( 'wp_head', 'custom_script_hook');
function custom_script_hook() {
?>
<script type="text/javascript" src="
<?php
$output='<script>
jQuery(document).ready(() => {
$("div#tm-extra-product-options").click(() => {
console.log("it working!")
});
});
</script>';
echo $output;
} | stackexchange-wordpress | {
"answer_score": 0,
"question_score": 0,
"tags": "php, javascript, jquery, headers"
} |
Is it possible to lock all new and existing WordPress posts to one specific author?
I have a case where there will be multiple users writing, editing, and publishing posts. All these posts should always have the same user as the author, a catch-all user if you will.
Is it possible to programmatically set the author for every new post to this user, no matter which user is logged in? I think I will be able to figure out how to remove the ability to change author on posts, but I am kind of stuck on this one question.
If someone could point me in the right direction I would be very thankful! | This is untested, but you could use the `wp_insert_post_data` filter to change the post author to a specific value whenever a post is inserted or updated:
add_filter(
'wp_insert_post_data',
function( $data ) {
if ( 'post' === $data['post_type'] ) {
$data['post_author'] = 2; // Replace with desired author's user ID.
}
return $data;
}
);
Just be aware that if posts are being created by users who do not have the `edit_others_posts` capability, such as Authors and Contributors, then they will experience unusual behaviour, because they will not have permission to do anything with the post once it has been saved. So they could see an error when the post page reloads after pressing Publish, for example. | stackexchange-wordpress | {
"answer_score": 1,
"question_score": 0,
"tags": "posts, author"
} |
Check for a specific taxonomy of a custom post type
I have a books custom post type, I want to do something only on the 'book_categories' pages and other stuff on the 'book_year' pages.
How do I check if I'm on those taxonomy pages? | Use `is_tax()`:
if ( is_tax( 'book_categories' ) ) {
}
if ( is_tax( 'book_year' ) ) {
} | stackexchange-wordpress | {
"answer_score": 2,
"question_score": 0,
"tags": "custom post types"
} |
Is there a maximum length to user passwords?
In the database, the hashed password is stored in a field that can store up to 60 characters.
My question: **is there an upper character limit** on the unhashed (user-chosen) passwords, **or will the hashing procedure always keep it below a certain length?** \- (Eg. how strictly should I validate its length upon registration?)
Edit:
Based on the article linked by Dave White, I've tried setting an 1001 character length password, just to see if it's possible. Although it almost froze the admin panel, but set it successfully, and login was possible.
Looks like the hasing algorithm shortens even the longest of passwords to a certain length, but I would like to hear confirmation from people more knowledgable in cryptography. | From WordPress Tavern \- the article is for WordPress password-protected posts but the final paragraph reads:
> This update only affects password-protected posts. **WordPress user passwords** don’t share the same length restrictions and **can be upwards of 1,000 characters long if so desired.** | stackexchange-wordpress | {
"answer_score": 1,
"question_score": 1,
"tags": "user registration, password, validation"
} |
How can I change "page" (as in foobar.com/page/5) to another word?
I would like the URLs for "pages" on my blog (which is to say the collections of titles and excerpts fpr 10 entries) to be called something else, such as "groups", so that the URL for the page for the 10 most recent entries would be `www.[foobar].com/group/1`, and so on. How can this be achieved? | Try this:
function re_write_rules() {
global $wp_rewrite;
$wp_rewrite->pagination_base = 'group';
$wp_rewrite->flush_rules();
}
add_action('init', 're_write_rules'); | stackexchange-wordpress | {
"answer_score": 0,
"question_score": 0,
"tags": "pages"
} |
show_in_rest false disable Gutenberg
When I declare a CPT with
'show_in_rest' => false,
Gutenberg editor is disabled for that post type. Is this an expected behavior? | Yes it is. As noted in the documentation for `register_post_type()` (emphasis mine):
> **'show_in_rest'**
> _(bool)_ Whether to include the post type in the REST API. **Set this to true for the post type to be available in the block editor**.
This is because the block editor (Gutenberg) is completely powered by the REST API. If the post type is not accessible via REST then the block editor cannot load or save the post. | stackexchange-wordpress | {
"answer_score": 3,
"question_score": 2,
"tags": "custom post types, block editor"
} |
Display time as "12:00 noon" instead of "12:00 pm"
We display event dates/times via Wordpress date and time functions in am/pm time (12 hour, not 24 hour). For any times that are noon - i.e. "12:00 pm" - we'd like to display "12:00 noon" instead.
And we'd also like to display "12:00 midnight" instead of "12:00 am".
This is to avoid confusion (we run online events around the world at different times so there is room for this type of confusion).
All other times of the day can keep their am/pm, it's just these two exact times that we're seeking to change. | So what you need to do is make your life easier and instead of searching everything within every instance of `.pp-post-content` or `.pp-post-content p`, let's wrap the times or the times in question with a span tag. Like you suggested in your comments `<span class="tas-event-time">` is sufficient enough.
Now, in your .js file, you want to add the following:
jQuery( document ).ready( function($) {
$( '.tas-event-time' ).html( $( '.tas-event-time' ).html().replace( '12:00 pm','12:00 noon') );
} );
That will, once the document is ready, change the instances of _'12:00 pm'_ to _'12:00 noon'_. | stackexchange-wordpress | {
"answer_score": 2,
"question_score": 0,
"tags": "date time, timezones"
} |
How to edit user_id on the comment edit screen
All guest comments are `user_id = 0`, while registered users have their unique `user_id` attach to the comment. How to edit comment `user_id` from the comment edit screen.
I think I need to use edit_comment and add_meta_boxes_comment hooks. | Thanks, everyone for the answers. I already solved it. This is my code. I was trying `edit_comment` at the time of questioning.
function wp_review_id_metabox_full() {
if (get_comment_type($comment->comment_ID) == 'wp_review_comment') {
add_meta_box('some_meta_box_name', __( 'ID: ' ), 'wp_review_id_metabox', 'comment', 'normal', 'high' );
}}
add_action( 'add_meta_boxes_comment', 'wp_review_id_metabox_full' );
function wp_review_id_metabox( $comment ) { ?>
<input type="text" name="new_user_id" value="<?php echo $comment->user_id; ?>"/>
<?php }
function wp_review_id_save_comment( $comment ) {
$comment['user_id'] = $comment['new_user_id'];
return $comment;
}
add_filter( 'wp_update_comment_data', 'wp_review_id_save_comment' ); | stackexchange-wordpress | {
"answer_score": 1,
"question_score": 2,
"tags": "users, comments"
} |
Wordpress hosting good practice
Hello Wordpress developers, I need advice from you.
I need to host Wordpress site for a client and I decided to use recommended hosting providers like Blue Host, Site Ground and Namecheap.
So what is recommended practice? Should a client register his account and buy hosting service with his own credit card and provide hosting/server/database access to me or I should register my personal account and pay hosting service with my card? | This seems off-topic, but I'll answer anyway.
It entirely depends on your arrangement with the client, as well as whether you want to take care of supporting your client's site after you deliver it to them.
Reputable hosts like wpengine.com provide different levels of access via developer roles: your client pays for everything and has access to everything, then invites you to their account and you have access to all the technical and support tickets functionality needed to do your work (but not the invoicing).
P.S.: Not affiliated with Wpengine, I just know for a fact they provide what I described above. | stackexchange-wordpress | {
"answer_score": 1,
"question_score": -1,
"tags": "hosting, shared hosting, hosting recommendation"
} |
password reset link being sent as HTTP?
I was just added as an admin on a WP site. The first thing I noticed is that the "(re)set your password" link in the email starts with **
How do I fix that? The "View Post" link in Comment moderation also uses HTTP, and possibly others as well (I haven't finished looking). | Your site is probably marked down as
< goto Settings and change WordPress Address (URL) from < to < Site Address (URL) from < to < | stackexchange-wordpress | {
"answer_score": 1,
"question_score": 1,
"tags": "wp admin, urls, security"
} |
How do I make my site multi language?
I started getting international visits but how do I make my site multi-language? Is there a good plugin or what do I have to do? | Depends of the setup, but in most cases this one was the best translation plugin I've used so far:
Free Version: <
Premium Version: < | stackexchange-wordpress | {
"answer_score": 0,
"question_score": 0,
"tags": "plugins, multi language"
} |
Copying a modified theme from one wordpress site to another wordpress site
So, I have one website which was using a theme called "theme-xyz". In past, I directly made modifications to this theme, in header, footer and style. Now, I want to copy this modified theme to a new wordpress website.
However, the new wordpress website already has "theme-xyz" and I can not remove/replace it under any circumstance. So I decided to rename my modified theme to "theme-xyz-new". However, this looses some functionalities, which I think are dependent on some php code which uses $theme-xyz variable. I could go through the whole code and rename the variable but that would be a lot of work.
Also, I think that I cant use child theme. If I am correct, to use child theme, I will also need the modified parent "theme_xyz" from older website but I cant move it with the same name as the new website already has "theme_xyz" and I cant replace that.
Any suggestions? Thanks for your help. | I know it may seem like a lot of work but I build all my themes from my own theme framework and in the framework I have a bunch of “placeholder” variables and texts that I just replace with my text editor’s “Find & Replace” function.
Additionally, EVEN if both themes have the same variable names, there shouldn’t be any conflict because only one can be active at a time, so only one theme has it’s code being executed.
Simply make sure the version numbers are different, make sure the folder/directory name is different and upload. Then using the version name, make sure your newer one is Activated. At this point, if you see errors or anything missing it could be down to several things. Options not being set in the new theme, missing widgets which are easy to drag from the Inactive Widgets section, or maybe there’s hard coded URLs or assets in the theme, which is poor practice and should be corrected anyway. | stackexchange-wordpress | {
"answer_score": 0,
"question_score": 0,
"tags": "theme development, themes, child theme, parent theme"
} |
How to add shortcode to HTML file (not showing on website)
Im trying to add a plugin shortcode into an HTML document so that when you clickthe "Music" icon on the site a popup appears with the plugin widget in it.
This is the shortcode in the HTML file (using the plugin "Custom CSS & JS), ive wrapped it in a div, it works with an iframe but I cant get a shortcode to appear.
[lbg_audio3_html5 settings_id='1']
This is the page - < | Shortcodes work because WordPress is set up to parse them when it outputs content. Including a shortcode in any plain HTML file won't work because there's nothing but the web browser to parse the code.
It's possible to include some WP methods - such as in this question What is the correct way to use WordPress functions outside WordPress files? \- but you'd likely be better off just taking the full HTML the shortcode outputs and pasting that into your file, rather than trying to bootstrap WP into HTML. | stackexchange-wordpress | {
"answer_score": 0,
"question_score": 1,
"tags": "shortcode, html"
} |
Styles don't load correctly. Insecure content
I'm a newby developing plugins for Wordpress.
When I try to enqueue a style, Wordpress shows the following error: Insecure Content.
The code I use to 'attach' the css files is the following one:
add_action('wp_enqueue_scripts', 'callback_for_setting_up_scripts');
function callback_for_setting_up_scripts(){
wp_register_style('estilo', __DIR__ . '/assets/css/estilo.css');
wp_enqueue_style( 'estilo' );
}
This code is located in the `/modules` folder of the main plugin because it's the style for a specific module.
I use Query Monitor Plugin as a debugger.
Any idea?
Thanks in advance | `__DIR__` returns the current file system path, not a URL. So the resulting stylesheet will not be a valid URL, and will not have ` causing the insecure content warning.
To get the URL for a stylesheet in your plugin, you need to use `plugins_url()`:
wp_register_style( 'estilo', plugins_url( 'assets/css/estilo.css', __FILE__ ) );
The use of `__FILE__` here is described in the documentation for the function:
> A full path to a file inside a plugin or mu-plugin. The URL will be relative to its directory. Typically this is done by passing `__FILE__` as the argument. | stackexchange-wordpress | {
"answer_score": 1,
"question_score": 0,
"tags": "plugin development, css"
} |
Is there a best practice remediation for PhpStorm's warning that void function the_post_thumbnail is used?
In a plugin I'm working on there is a line:
`echo the_post_thumbnail(array(155,55));`
It throws a inspection warning:
> 'void' function 'the_post_thumbnail' result used
Is there a best practice method of dealing with this or is the PhpStorm inspection overly aggressive? | The solution is simple, don't `echo` the result of that function, there is no result to echo.
echo the_post_thumbnail(array(155,55));
Is equivalent to something like this:
echo '';
the_post_thumbnail(array(155,55));
Functions that begin with `the_` in WP don't return things, they output things. Some of them let you pass a parameter that lets them return instead, but those are the exception, also don't do that.
The `echo` is both unnecessary, and incorrect PHP.
So, just use this:
the_post_thumbnail([ 155, 55 ]);
Notice I also swapped the old style array syntax for modern array syntax, and spaced out the parameters. | stackexchange-wordpress | {
"answer_score": 3,
"question_score": 0,
"tags": "plugins, functions, post thumbnails"
} |
Child them function.php 'parent-style': should I name this as parent theme name?
When creating child them and setting up the initial function.php content:
<?php
add_action( 'wp_enqueue_scripts', 'my_theme_enqueue_styles' );
function my_theme_enqueue_styles() {
$parent_style = 'parent-style'; // <=====HERE
wp_enqueue_style( $parent_style, get_template_directory_uri() . '/style.css' );
wp_enqueue_style( 'child-style',
get_stylesheet_directory_uri() . '/style.css',
array( $parent_style ),
wp_get_theme()->get('Version')
);
}
In this exemple should I rename 'parent-style' as the name of the parent style? Or leave it as 'parent-style'? | You can leave it as is _(see Jacob Pettie's comment)_ or you can change it, but the key here is to add the path to locate the parent theme’s CSS.
<?php
add_action( 'wp_enqueue_scripts', 'my_theme_enqueue_styles' );
function my_theme_enqueue_styles() {
wp_enqueue_style( 'parent-style', get_template_directory_uri() . '/style.css' );
}
In your example you’re cutting it off after the ( ‘parent-style’ ), but you should continue and include the path to the parent theme’s style.css.
get_template_directory_uri() is for the parent theme.
The full step by step breakdown can be found here: < | stackexchange-wordpress | {
"answer_score": 1,
"question_score": 1,
"tags": "child theme"
} |
Permalinks for parent/child pages and custom post types
I have this custom structure set for my permalinks: /archive/%postname%
With this, my URLs show as example.com/parent/child, which is the desired behavior. However, I'm adding a custom post type and this permalink structure is causing undesired URLs for the CPT. I want the permalink to be example.com/news/headline, but I'm getting example.com/archive/news/headline.
Here's my CPT:
register_post_type('news', array(
...
'public' => true,
'rewrite' => array('slug' => 'news'),
'supports' => array( 'title', 'page-attributes', 'editor', 'custom-fields')
));
Is there a better permalink structure I could use to achieve the URLs I require? Or is there something missing/wrong in my CPT that would fix this issue? | Disable the `with_front` on `rewrite` while `register_post_type`.
In your case:
register_post_type('news', array(
...
'public' => true,
'rewrite' => array('slug' => 'news', 'with_front'=> false),
'supports' => array( 'title', 'page-attributes', 'editor', 'custom-fields')
)); | stackexchange-wordpress | {
"answer_score": 1,
"question_score": 1,
"tags": "permalinks"
} |
Adding code before post title with the_title produces weird results
add_action ('the_title' , 'test');
function test($title) {
$mycode = '<div>test</div>';
echo $mycode . $title;
}
I expected this functions.php code to add "test" before the post title. It does that. But it adds it also all over the place on the page. Not sure what's the logic, it seems it adds appends it to all menu items of the page.
Am I wrong on my usage of the_title? Or might there be theme interference here? | `the_title` filter has two parameters passed to it, `$title` and `$id`. You could use the `$id` to check the current post type and then do stuff based on that.
add_action ('the_title' , 'test', 10, 2);
function test($title, $id) {
return 'post' === get_post_type($id) ? '<div>test</div> ' . $title : $title;
}
The problem with this is that the filter is kind of not aware in which context it is called ( _naturally WP conditionals provide some context_ ). So you might get unexpected results and end up with the custom title prefix/suffix showing up everywhere on a single view, e.g. the main menu, main title, related posts, sidebar, footer..., even if you just wanted to make the modification in only one part of your view. This of course depends on your setup, needs and use case. | stackexchange-wordpress | {
"answer_score": 1,
"question_score": 0,
"tags": "functions, hooks, actions"
} |
How to hide wordpress post comment form for specific role
How to hide "comment_form();" for Author role in wordpress? What i need to add in comments.php? | You can hook to the `comments_open` filter.
add_filter('comments_open', function($open, $post_id){
if(in_array( 'author', (array) wp_get_current_user()->roles){
return false;
}
return $open;
}, 10, 2); | stackexchange-wordpress | {
"answer_score": 1,
"question_score": 0,
"tags": "comments, forms"
} |
How to wordpress multi site
I am setting up a wordpress for a friend, how do I make it so I can control both websites at once? | I think to explain it all here is a bit beyond the scope. Perhaps it is best to start here, and then you can ask detailed questions if you encounter problems:< | stackexchange-wordpress | {
"answer_score": 2,
"question_score": 0,
"tags": "multisite, network admin"
} |
htaccess wildcard redirect misses some URLs
I am using a wildcard redirect to redirect my old domain to a new domain. It works great but misses a few URLs (they don't get redirected to the destination and return status 200)
Can you please help me understand what's wrong with this? Maybe I am doing the wildcard redirect incorrectly or it's a server issue. My old domain is `old.example` and my new domain is `new.example`.
Example URL which isn't getting redirected: `old.example/example-url`
Here's my `.htaccess` file:
# BEGIN WordPress
<IfModule mod_rewrite.c>
RewriteEngine On
RewriteBase /
RewriteRule ^index\.php$ - [L]
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule . /index.php [L]
</IfModule>
# END WordPress
#Options +FollowSymLinks
# Redirect everything
RewriteRule ^(.*)$ [R=301,L] | You've put the redirect directive in the wrong place. It needs to go _before_ the WordPress front-controller, otherwise, the redirect will simply get ignored for anything other than URLs that map directly to the filesystem.
Since these domains are also on the same server (same hosting account I assume) then you will need to check for the requested hostname, otherwise, you'll get a redirect loop.
For example:
# Redirect everything from old to new domain
RewriteCond %{HTTP_HOST} ^old\.example [NC]
RewriteRule (.*) [R=301,L]
# BEGIN WordPress
# :
The regex `^(.*)$` can be simplified to `(.*)` since regex is _greedy_ by default. | stackexchange-wordpress | {
"answer_score": 1,
"question_score": 1,
"tags": "redirect, htaccess"
} |
How to get specific image in media library with php
I am new to Wordpress. I am trying to get an image src from one of my images in my media library without having to mention my domain or having to do some external link.
Say I have an image with an id of 20,
instead of writing something static like,
"`<img src ="
I could do something like "`<img src="<?php echo get_image_by_id(20); ?>">`".
I know get_image_by_id function doesn't exist but is there anything similar to that? | There's a few functions:
* `wp_get_attachment_image_url( $attachment_id, $size )` \- Gets the URL to specified size of the image.
* `wp_get_attachment_image_src( $attachment_id, $size )` \- Gets an array of the image URL, width, and height for the specified size of the image.
* `wp_get_attachment_image( $attachment_id, $size )` \- Gets the full HTML for an image, including width, height, alt, sizes and srcset attributes. If you intend on outputting an HTML `<img>` tag, use this. | stackexchange-wordpress | {
"answer_score": 1,
"question_score": 1,
"tags": "php, functions, images"
} |
How to replace home link anchor text with image
I'm trying to replace home link text with an image for breadcrumb trailer. Mouse cursor is still pointer but image doesn't appear. I'm using this breadcrumb trailer
How could I this working please jsfiddle
<li itemprop="itemListElement" itemscope itemtype="" class="trail-item trail-begin">
<a href="#" rel="home" itemprop="item"><span itemprop="name">Home</span></a>
<meta itemprop="position" content="1" />
</li>
CSS:
li.trail-begin {
display: inline-block;
font-size: 0;
color: 000;
height: 25px;
position: static;
text-align: center;
width: 30px;
line-height: 25px;
margin: 0;
}
li.trail-begin a {
background-image: url("
background-position:left;
background-repeat:no-repeat;
background-size: 25px;
} | Your question is much more like a CSS question. The anchor a by default is display as inline. So it doesn't have height and width unless text, image etc inside with finite dimension. To make it work, just add `display:block;` to the css so it expands to match the parent container.
li.trail-begin {
display: inline-block;
font-size: 0;
color: 000;
height: 25px;
position: static;
text-align: center;
width: 30px;
line-height: 25px;
margin: 0;
}
li.trail-begin a {
background-image: url("
background-position:left;
background-repeat:no-repeat;
background-size: 25px;
display: block; /* <-------- */
} | stackexchange-wordpress | {
"answer_score": 0,
"question_score": 0,
"tags": "navigation, breadcrumb"
} |
How to return site_url() without https://
I am retrieving the site URL and creating a shortcode to display it. However when i return the site URL as expected it contains the full string including https://
How can i return the site url without the ` part? So instead of < it would just say siteurl.com
add_action( 'init', function() {
add_shortcode( 'site_url', function( $atts = null, $content = null ) {
return site_url();
} );
} ); | Try below method
$site_url = site_url();
$url = preg_replace("(^https?://)", "", $site_url );
return $url; | stackexchange-wordpress | {
"answer_score": 1,
"question_score": 0,
"tags": "php, site url"
} |
wordpress and add actions to button by coding
I create my action in functions.php
add_action('wp_ajax_myfilter', 'misha_filter_function'); // wp_ajax_{ACTION HERE}
function misha_filter_function()
{
echo "my button action";
}
How can i create button to call this method `wp_ajax_myfilter` | Try below method.
<a id="view_site_description" href="javascript:void(0);">View Our Site Description</a>
add_action( 'wp_footer', 'add_js_to_wp_footer' );
function add_js_to_wp_footer(){ ?>
<script type="text/javascript">
jQuery('#view_site_description').click(function(){
jQuery.ajax({
type: 'POST',
url: ajaxurl,
data: {"action": "myfilter"},
success: function(data){alert(data);}
});
return false;
});
</script>
<?php } | stackexchange-wordpress | {
"answer_score": 1,
"question_score": 1,
"tags": "ajax"
} |
remove duplicate name submenu link from the custom post type
I was wondering what would be the proper way to remove submenu with duplicate name in custom post type in the admin. I tried to use `remove_submenu_page()` however since its a duplicate it is showing same slug for menu and submenu `/wp-admin/edit.php?post_type=portfolio` and to use that function my understanding slugs should be different
 | stackexchange-wordpress | {
"answer_score": 0,
"question_score": 0,
"tags": "custom post types, admin menu"
} |
Custom failed login error messages for users based on user role?
Is there a way to give users that belong to a certain user role a unique error after failing to login?
Basically, I imported users from a site with a different CMS and it was near impossible to import their passwords. I would like to have the users of the older site belong to a specific user role to get an error saying due to the redevelopment of the website, they need to reset their passwords for security purposes. | You can hook to the `wp_login_errors` filter.
add_filter('wp_login_errors', function($errors, $redirect_to){
if(isset($errors->errors['incorrect_password']) &&
in_array('custom_role', (array) get_user_by('login', $_POST['log'])->roles)){
$errors->errors['incorrect_password'][0] = 'Custom message';
}
return $errors;
}, 10, 2);
EDIT:
This should work with WooCommerce login form or any other form that implements `wp_signon`:
add_filter('authenticate', function($user, $username, $password){
if(is_wp_error($user) &&
isset($user->errors['incorrect_password']) &&
in_array('custom_role', (array) get_user_by('login', $username)->roles)){
$user->errors['incorrect_password'][0] = 'Custom message';
}
return $user;
}, 21, 3); | stackexchange-wordpress | {
"answer_score": 0,
"question_score": 0,
"tags": "login, user roles"
} |
The option to change site language isn't available
I have a Wordpress installation that's set to English by default, but I want to change it to Polish. From what I found, there's supposed to be an option in Settings -> General, right below "Week Starts On", but there's nothing there. How can I change the site's language? I don't want a multi-language site or anything complex like that, I just want to fully switch to Polish. | I think its because of your low network bandwidth and if you wait in general tab or connect to better network, it will appear there. The reason is this part (new languages) needs to be downloaded from network. | stackexchange-wordpress | {
"answer_score": 1,
"question_score": 0,
"tags": "language"
} |
Debug Errors, site health
When I go to site health this is what I am seeing.
Debug mode is often enabled to gather more details about an error or site failure, but may contain sensitive information which should not be available on a publicly available website.
The value, WP_DEBUG_LOG, has been added to this website’s configuration file. This means any errors on the site will be written to a file which is potentially available to normal users.
What should the file be? I looked at < and I did not see what the file is support to be. | You should be looking for the `wp-config.php` file in the root of your WordPress installation. From the documentation in the WP_Debug Section
> `WP_DEBUG` is a PHP constant (a permanent global variable) that can be used to trigger the “debug” mode throughout WordPress. It is assumed to be false by default and is usually set to true in the wp-config.php file on development copies of WordPress. | stackexchange-wordpress | {
"answer_score": 1,
"question_score": 0,
"tags": "debug"
} |
if in category but only with post meta
Working on an if statement to display text only if it's in a specific category WITH specific post meta. If the post meta doesn't match but it's in this category, the text should not display. This is showing the text even if it's not the the " **secret category** " category. I don't know what to do beyond this.
if( in_category('secret-category') && $stat == 'NFS Stat' || $stat == 'Sold Stat' )
{
echo 'Do something here.';
} | It looks like you just have an operator precedence issue.
Your logic here will always return true if $stat == 'Sold Stat' regardless of the result of in_category('secret-category').
Try this, the extra parenthesis will force the || statement to be evaluated separately:
if (in_category('secret-category') && ($stat == 'NFS Stat' || $stat == 'Sold Stat')) {
echo 'Do something here.';
} | stackexchange-wordpress | {
"answer_score": 1,
"question_score": 0,
"tags": "posts, customization, categories, custom field, post meta"
} |
Fill custom select field with pages/post titles
I'm just getting into the world of SAGE development and at the same time, I'm using the Advanced Custom Fields plugin.
Let's say, that we have created two custom post types (Professors, Lessons). Each post type has its own custom fields. At some point, however, I would like to add a new custom field to the Professors' post type that will be called Lessons and will be a selectable list of all the lessons that one created in the Lessons post type. So In that way, you can connect each professor with the corresponding lessons of his/hers.
So far I couldn't find a way to pre-fill/pre-define a custom select field with values taken from the database (e.g post titles). Is there a different way to achieve this? | You could use post object or post link as your custom field type. < | stackexchange-wordpress | {
"answer_score": 1,
"question_score": 0,
"tags": "database, advanced custom fields, select"
} |
How to modify WCMP Rest API response?
I had tried the `register_rest_field()` to modify the Rest API response of the WCMP plugin, but it seems that this function applies only to the default wordpress REST API (wp/v2).
The purpose of modifying is that vendors data (fetched from this URL ...wp-json/wcmp/v1/vendors) does not include the image's URL for each vendor, instead the image ID is returned, and I don't want to make another API request just to get the image URL based on the ID.
Adding the `_embed` parameter did not work.
How can I modify the response of the WCMP like the `register_rest_field()` do with default REST API in order to include the image URL? | Finally I had solved it!
In the source code of the plugin "dc-woocommerce-multi-vendor", I had viewed the class "class-wcmp-rest-vendors-controller.php" and figured out that they are using this filter in order to gather up the fields of the response: `apply_filters("wcmp_rest_prepare_vendor_object_args", array(...));`
In the functions.php of the child theme I had written this code to edit the filter:
function modify_rest_api_vendor_response( $arg ) {
$arg["shop"]["image"]=wp_get_attachment_url($arg["shop"]["image"]);
return $arg;
}
add_filter( 'wcmp_rest_prepare_vendor_object_args', 'modify_rest_api_vendor_response', 10, 3 );
And now I can get the image URL
**Hope that it could help somone...** | stackexchange-wordpress | {
"answer_score": 0,
"question_score": 1,
"tags": "plugins, plugin development, woocommerce offtopic, rest api, api"
} |
Doing $wpdb->get_results returns NULL, doing the same query in my DB returns correct value
I have this query to do in my code:
function get_item($id){
global $wpdb;
$post_id_query = "SELECT * FROM wp_postmeta WHERE post_id = ". $id ." AND meta_key LIKE '%main%'";
$call_post_id_call = $wpdb->get_results($wpdb->prepare($post_id_query));
return $call_post_id_call;
}
$main_item = get_item(34487);
If I run `SELECT * FROM wp_postmeta WHERE post_id = 34487 AND meta_key LIKE '%main%'` on my DB it works...
I'm not very keen on wordpress to be honest. | The following script will help you to identify if there any error exists in the query.
$wpdb -> show_errors ();
$call_post_id_call = $wpdb->get_results($wpdb->prepare($post_id_query));
$wpdb -> print_error (); | stackexchange-wordpress | {
"answer_score": 0,
"question_score": 0,
"tags": "wp query, query, wpdb"
} |
Developing a plug-in to charge for
Perhaps I'm not using the right search terms but I can't find how to develop a WordPress plugin that I want to make available on a subscription or purchase plan. When I try to Google this topic, woocommerce fills up all of the search results. I'm looking for how other developers disable their plugins for non-payment for example so I assume their is a database hook I can make to call home or something?
I've googled, "how to code a WordPress plugin that I want to sell" and all I get back are marketing tips. While those links are good, it's not what I am after at this time. | I can't comment yet so I'll comment here.
Start here:
<
That'll give you the basics. Hope you realize the can of worms you're getting into... payment gateway api's, registration codes, managing updates, etc. Self-hosting a plugin on your own is not for the feint of heart.
I know a number of years ago there was a company that took care of a lot of that for you, including registration & payments. Can't seem to find them now though.
_edit_ found them. < | stackexchange-wordpress | {
"answer_score": 1,
"question_score": 0,
"tags": "plugin development"
} |
Google Maps for Woocommerce Checkout
I am looking to integrate a Google Maps into the woocommerce checkout page, wherein, the customer, while checking out has to select his/her Google Maps location, it gets stored for each order and then it can be seen in the edit order page of the wordpress backend. Any ideas on how to do this or plugins that can work? | I am looking for a similar thing at the moment and am investigating 2 different plugins:
* <
* <
I will be trying out the second plugin first, as it is free. Hope that helps
(UPDATE) Neither of the above plugins did the job unfortunately, I would not recommend | stackexchange-wordpress | {
"answer_score": 0,
"question_score": 0,
"tags": "plugins, php, woocommerce offtopic, google"
} |
Accessing internal wordpress site from the web
My webserver(WordPress) is running Apache on localhost port 80 with dedicated public IP. On the Firewall I have configured a SNAT rule:
HTTP policy - (From Anyone on the web) > (using public IP) > (send traffic to Internal IP)).
I can confirm SNAT works to an extend. I can access the wordpress page through the public IP. However, the site doesn't load properly. CSS and images are gone and the whole layout is decremented:
When trying to /wp-admin, the external user sees "localhost/xxx" and connection is lost.
Image 1 and 2
Just to mention, my site runs Apache24 with phpmyadmin, php7.4, MySQL and WordPress 5.4.
If any info is needed let me know.
Edit: phpmyadmin is accessible and I can login without any problems. This must indicate that the issue is a wordpress configuration. Nevertheless, I hope someone can help :-)
Image: phpmyadmin access via public IP | So I managed to fix it by changing both SiteURL and homeURL to being the exact same. Now I've finally added an A-record in my DNS so the sites uses its own URL. Works like a charm :)
Im not sure why but I've seen others place " for SiteURL and "< for homeURL. However, this wouldn't work in my case even. Hope it can help other who face the same problem. | stackexchange-wordpress | {
"answer_score": 0,
"question_score": 0,
"tags": "static website"
} |
How Does comment_author Filter Work?
I want my plugin to add extra text after a comment author's name. For example if they've commented as "Albert", I might want the comments section to display their name as "Albert (genius)".
I'm trying to use the comment_author filter as follows, but it doesn't seem to have any visible effect:
function my_author_filter($author) {
return $author . '( genius)';
}
add_filter( 'comment_author', 'my_author_filter');
Thanks | Sometimes themes call `get_comment_author` instead, and bypass the comment_author function. Try using that filter instead. | stackexchange-wordpress | {
"answer_score": 1,
"question_score": 1,
"tags": "filters, comments, author"
} |
How to simulate web traffic to test performance of a website
I have to test a WordPress site performance on an Ubuntu server running on apache2 and mysql, what the best way to simulate web traffic to see how the theme, plugins, database, cpu, and ram is performing? | I think what you are looking for is Jmeter's Access Log Sampler: <
You can use that to replay your Apache logs at various volumes and concurrences. | stackexchange-wordpress | {
"answer_score": 0,
"question_score": 0,
"tags": "mysql, performance"
} |
How to let users create lists of woocommerce products?
I've almost finished my website < It's a french database of plants to create of forest garden (free and collaborative) built with wordpress and woocommerce.
**I'd like to give users the ability to create lists of plants.**
> ie: bookmark 5 plants in a list called 'my forest 1' and bookmark 10 plants in another list called 'my forest 2' displayed like this (which is the shop layout). {
global $wpdb;
$query = 'SELECT name FROM `wp_terms` WHERE slug = "' . $slug . '"';
$getname = $wpdb->get_results($query);
$name = $getname[0]->name;
return $name;
} | stackexchange-wordpress | {
"answer_score": 0,
"question_score": 0,
"tags": "woocommerce offtopic, tags, slug"
} |
How come a YouTube link isn't transformed into a shortcode inside the post content?
Assume I wanted to add the following video link ` inside a post, in a non-Gutenberg environment.
What happens is WordPress actually displays the `iframe`, so, there is some wrapping being done...somewhere, but I don't exactly know where that is.
What's going on here?
How does WP transform that link to an iframe and make it pretty? The reason for asking this is because there's absolutely no way to take that link from a search within the post and then grabbing its output. **To me, the developer, it's just a link whose output that an user sees I cannot reproduce.** | On output WordPress parses the content and finds any links on their own line and for links from supported sites it uses oEmbed to get the embed code for the linked media and replaces the link with it.
It does this with `WP_Embed::autoembed()`, which is added as a filter to `the_content`. | stackexchange-wordpress | {
"answer_score": 1,
"question_score": 0,
"tags": "posts, shortcode"
} |
Query for current post
I want to show current post.I will use this query in single template for custom post type.When click the custom post type, only the post will shown.
How can I write this query?
In wordpress developer page, $post exists as a query arg.But there is no how to use $post arg.
I write this : $post=get_post(); but it didnt work.How can I write $post as a arg in query array? | You shouldn't be writing any query. WordPress does this for you. You `single-{post type}.php` template should only contain the standard loop:
<?php
if ( have_posts() ) :
while ( have_posts() ) : the_post();
// Display post content
endwhile;
endif;
?> | stackexchange-wordpress | {
"answer_score": 0,
"question_score": -1,
"tags": "wp query, query posts, meta query"
} |
Can I "protect" a page with a form asking for an email address?
I am developing a viewing room for an art gallery. Viewing rooms are pages with content that can only be seen by visitors if they provide their email address to add them to a newsletter. Something like the following site: <
I know that pages and posts in WordPress can be password protected, but I don't need this type of protection. Is there any action I can hook to do this? Basically, I need to show a form so visitors can type their email address. Once they do this, they are added to a newsletter (a Mailchimp one, for example), and then the actual page is shown. Also, a cookie must be set so they don't have to provide their email address again to access this page in the future.
Thanks in advance | What about filtering `the_content`?
function se365701_require_email ( $content ) {
if ( is_page( 'require_email' ) ) && !isset( htmlspecialchars( $_COOKIE['submitted_email']) ) {
return $form; // your MailChimp Form Code
} else{
return $content;
}
add_filter( 'the_content', 'se365701_require_email' );
Note that your form provide itself may have a cookie or you may need to set it when the form is filled out. You could also perhaps use `$_POST[]` or `$_GET` instead. You just need some way of knowing if the form was submitted. | stackexchange-wordpress | {
"answer_score": 1,
"question_score": 0,
"tags": "pages, hooks, user access, cookies, authentication"
} |
Wordpress shows different upload_max_filesize than php.ini setting
I have php.ini files in the following directories of my WordPress installation:
* /wp-admin
* /wp-content
* / (where there wp-config.php lies)
In all of them I set `upload_max_filesize = 640M;` \- **640MB** is the maximum value that is allowed by my provider in my package (I called).
memory_limit = 268435456;
post_max_size = 67108864;
upload_max_filesize = 640M;
I did NOT configure an upload_max_filesize in wp-config.php or in .htaccess. I confirmed this value with `phpinfo()` and with `ini_get('upload_max_filesize')`.
Nonetheless, WordPress displayes **64 MB** as maximum on the media upload page and on the WooCommerce status page.
I am utterly puzzled. I checked every post on stack but I couldn't find an answer to that dissonance. Help would be much appreciated.
 {
'use strict';
})( wp.customize, wp, jQuery );
what is **api** , **wp** and **$** at the top and **wp.customize** , **wp** , **jQuery** at the bottom mean? | It's an Immediately Invoked Function Expression (IIFE) - an anonymous function that executes itself after it has been defined. The variables at the bottom are taken from the global scope and are passed as parameters to the anonymous function.
So `api` represents `wp.customize`,
`wp` represents `wp` and
`$` represents `jQuery` inside the function. | stackexchange-wordpress | {
"answer_score": 2,
"question_score": 0,
"tags": "plugin development, javascript, jquery"
} |
How to exclude specific post_type from default search?
I'm trying to exclude WooCommerce products from default WP search, but I need to keep all other posts types, including CPT and those CPT created in the future. Im trying with:
function searchFilter($query) {
if (!$query->is_admin && $query->is_search) {
$query->set('post_type', array('post', 'page', 'CPT'));
}
return $query;
}
add_filter('pre_get_posts', 'searchFilter');
In code above I can set in `post_type` what posts types I want to choose. But I would like to exclude only a 'products' post_type. Is there any way to create parameter like that? | If you want to exclude the "product" post type (= WooCommerce products) from all front-end searches on your site, you can use this code:
function my_adjust_post_type_args( $args, $post_type ) {
if ( 'product' === $post_type ) {
$args['exclude_from_search'] = true;
}
return $args;
}
add_filter( 'register_post_type_args', 'my_adjust_post_type_args', 10, 2 );
It modifies the "exclude_from_search" argument when the "product" post type is registered. See the docs for the register_post_type() function for more information. | stackexchange-wordpress | {
"answer_score": 0,
"question_score": 0,
"tags": "search"
} |
mystery tags which I didn't add - vulnerability?
I recently looked at the tags for my WP site and saw dozens of tags which I didn't add, and which seemed unrelated to any posts I've ever made. Many of them looked like random dictionary words. A handful of them had descriptions and a google search for the exact description text brings up many sites with the exact same tags, e.g. "8bit", "Mothership", "Nailed It", etc.
My question: how and by whom where these tags added? Are they installed by default by some plugin? Are they evidence of a vulnerability?
google search of example tag | The answer is that these tags are created as part of the unit-test suite of json-api WP plugin:
<
< | stackexchange-wordpress | {
"answer_score": 1,
"question_score": 1,
"tags": "tags"
} |
Custom post type for text box that appears on every page
I want to create a custom post type for an entry that will appear on every page of a website. A few other CMS's have a 'globals' entry type for this. How would I go about this using Wordpress? | I think the most popular way to do this is to use a widget in the installation. Or ACF pro provides a global field - but that's a commercial plugin. | stackexchange-wordpress | {
"answer_score": 0,
"question_score": 0,
"tags": "custom post types"
} |
How to change hover link colour for blog post (body) text only
I am using the Shamrock theme and I am happy with link colours on the main page however when you go into a blog post and hover over any links within the body they are red.
I have tried multiple things with CSS (after hours of googling as I do not know CSS) and without using !important and therefore changing ALL links I can't get just the links within the blog posts to change when hovering over them.
Is anyone able to help with this, please? | Found the answer! For anyone else with the this question, this worked for me:
.entry-content a:not(.more-link):not(.wp-block-button__link):hover {
color: blue;
}
Change colour for one you prefer :) | stackexchange-wordpress | {
"answer_score": 0,
"question_score": 0,
"tags": "css, links"
} |
Get single post from tags array
I have wordpress and many posts. Every post have on tag. Posts may have same tags.
I have:
post1 tag1 date1
post2 tag1 date2
post3 tag2 date3
post4 tag3 date4
post5 tag2 date5
I have get:
post1
post3
post4
That is, I want to select from all posts one post from posts with the same tag and the earliest by date of publication.
I assume the following algorithm:
1. Get all tags of blog
2. Get posts for each tag
3. Get last date post for each tag
4. Show all posts from step 3. | `$args = array( 'type' => 'post', 'orderby' => 'name' ); $tags = get_tags($args); foreach($tags as $tag) { $the_query = new WP_Query( 'tag='.$tag->name ); if ( $the_query->have_posts() ) { $the_query->the_post(); $desired_posts[] = get_the_ID(); // all the post IDs stored here. } else { // no posts found } wp_reset_postdata(); } $args1 = array( 'post_type' => 'post', 'orderby' => 'date', 'post__in' => $desired_posts, 'posts_per_page' => -1 ); $the_query = new WP_Query( $args1 ); `echo '<ul>';` if ( $the_query->have_posts() ) { while ( $the_query->have_posts() ) { $the_query->the_post(); `echo '<li>'. get_the_title() . '</li>';` } } else { // no posts found } `echo '</ul>';` ` | stackexchange-wordpress | {
"answer_score": 0,
"question_score": 1,
"tags": "loop"
} |
How to have different headers.php files based on the display page
With the `get_header()` function, if I have an `header.php` and an `header-news.php`, can I use the second file only when a single post of the nesw category is displayed? I have a one page wordpress website where the only page will be the news category archive and the sigle news categorized posts that are using the `single.php` file template. The menu links are anchor tags so if the user navigate away from home by clicking on a news, I need that the menu can redirect it back to the home where all the contents are published. Also I need some suggestion on how to paginate my category archive. Thanks in advance. | Please try this header in single.php
<?php get_header('news'); ?>
let me know if still facing the issue. | stackexchange-wordpress | {
"answer_score": 0,
"question_score": 0,
"tags": "php, theme development"
} |
How can I & how do I change text displayed in comment via child theme
This isn't a specific theme I'm asking for, well, yes it is, but I assume the answer would work on any theme..
I've recently learned little about child theme, but I'm not understanding how to change stuff. For example, the following code (see screenshot)
{
// Don't do anything if we're not in a single post
if(! is_singular()){
return $content;
}
$customClass = 'custom-class';
return preg_replace_callback(
'/<pre([^>]+)class="([^"]+)"/i',
function( $matches )use( $customClass ){
return '<pre' . $matches[1] . 'class="' . trim($matches[2]) . ' ' . $customClass . '"';
},
$content
);
} ); | stackexchange-wordpress | {
"answer_score": 0,
"question_score": 0,
"tags": "posts, functions, customization, themes, filters"
} |
Get full image array
When I use Advanced Custom Fields I can return the full image array of an upload. Is there a native WordPress way to get the full image array for any image in the Media Library by image ID? I can find ways to get the alt text and a specific image size, but not the array itself... | The "full array" is constructed by Advanced Custom Fields from various sources. It's not a format that occurs natively in WordPress.
If you want to output an image tag for an image with all the correct attributes, just use the ID with `wp_get_attachment_image()`. That returns an HTML `<img>` tag with the `src`, `width`, `height`, `alt`, `srcset`, `sizes` and `class` all populated. You can add or change attributes to the tag using the 4th argument:
echo wp_get_attachment_image(
$attachment_id,
'large',
false
[
'class' => 'custom-class',
'data-attribute' => 'custom-attribute-value',
]
);
To be honest, if your goal is to ultimately get an `<img>` tag, then even with ACF you should return an ID and use this function. | stackexchange-wordpress | {
"answer_score": 2,
"question_score": 1,
"tags": "images, advanced custom fields, media library"
} |
How to download file without login to wordpress account?
The following link is used to share individual customer/user to download invoice PDF file. But each time they have to login and download PDF file. I want this link should download PDF file without login by user. ` | I got solution that this plugin has setting to save pdf file in temp directory and has option to change temp directory. Then I added path to save files and that file is accessed directly to download file. Sorry for creating this post without looking into plugin's setting. | stackexchange-wordpress | {
"answer_score": 0,
"question_score": 0,
"tags": "links, user access"
} |
Is it possible not to load theme on a specific page in wordpress?
I have a question about wordpress, I need the current theme installed on my wordpress not to be loaded on a certain page, is it possible?
What I want to do is create a bootstrap dashboard, and I don't want to load the default theme. The idea is to develop a dashboard via plugin and generate all the html, header, content, footer.
I thought about using "WP_USE_THEME" and using external files, but I need to use wordpress functions like: add_action, add_shortcode and etc.
I accept suggestions too !!! Thank you. | Why not create a template file that gets loaded by the dashboard page? It is possible to create a template just like a theme template that actually lives in the plugin itself. That way, you can still call `wp_head()` and `wp_footer()` and have full access to WP functionality, but not actually pull in whatever theme the site is using.
Here's an answer that shows how to do it: How to add custom template in plugin? | stackexchange-wordpress | {
"answer_score": 1,
"question_score": 0,
"tags": "plugins, themes"
} |
How can I query and sort custom-post type using WP_Query
guys, I have a custom post type called "game" and it has some custom fields (get_post_meta) which I access by their keys "_game_date_key", "_game_home_goals_key" and "_game_away_goals_key".
How do I use the WP_Query() to return posts sorted by the "_game_date_key" and ("_game_home_goals_key" and "_game_away_goals_key") are numbers ? | You should add arguments to WP_Query to sort by your keys in the order you want. The compare value can be your filter (larger, smaller, etc)
$args = [
'meta_query' => array(
'relation' => 'AND',
'event_start_date_clause' => array(
'key' => '_game_date_key',
'compare' => 'EXISTS',
),
'event_start_time_clause' => array(
'key' => '_game_home_goals_key',
'compare' => 'EXISTS',
),
'event_start_time_clause' => array(
'key' => '_game_away_goals_key',
'compare' => 'EXISTS',
),
),
'orderby' => array(
'_game_date_key' => 'ASC',
'_game_home_goals_key' => 'ASC',
'_game_away_goals_key' => 'ASC',
),
]; | stackexchange-wordpress | {
"answer_score": 0,
"question_score": 0,
"tags": "custom post types, wp query, custom field"
} |
How toprint informations in footer
Is there any filter or hook to print a script or add in the footer some content? I'm not talking about `wp_enqueue_` function, I'm creating a plugin that will show a banner for privacy and cookie info and I want to append it to the footer. I'm using at the moment this code, but I hope that there is a more clean wey to do it:
function cookie_privacy_script()
{
<script>
// js code here
</script>
}
add_action('wp_enqueue_scripts', 'cookie_privacy_script'); | Printing content and adding a script to the footer are two different things.
If you want to add your banner html in the footer, you can use the `wp_footer` hook that will trigger when you call the `get_footer()` function from your theme.
You can simple echo your html (or load a template file).
function myplugin_wp_footer () {
echo '<div id="myplugin-cookie-banner">bla bla</div>';
// or you can use include() function to load a PHP script instead
}
add_action('wp_footer', 'myplugin_wp_footer');
Then you can add your JS script as suggested by @CRavon
function myplugin_cookie_privacy_script(){
wp_enqueue_script( 'myplugin-cookie-script', plugin_dir_url(__FILE__).'js/cookie-banner.js', [], true, true);
}
add_action('wp_enqueue_scripts', 'myplugin_cookie_privacy_script');
The last parameter of `wp_enqueue_script` tells that your script will be added in the HTML at the end of the body. | stackexchange-wordpress | {
"answer_score": 0,
"question_score": 0,
"tags": "theme development"
} |
HTML showing after PHP code in <img> tag
I am trying to display a page featured image. Every time I use the img tag,the text after the php code (" class="headshot" >) displays below the picture on the website. See picture screenshot of picture below ;?>" class="headshot">
</div> | This is because `the_post_thubmnail()` outputs an `<img>` tag. So the result of your code will be something like this:
<div class="bio-picture">
<img url="<img src="thumbnail/image/url.jpg" class="wp-post-image attachment-full">" class="headshot">
</div>
Your screenshot is how the browser has chosen to handle that broken HTML.
If you want to output the post thumbnail `<img>` with a custom class, use this:
<div class="bio-picture">
<?php the_post_thumbnail( 'full', array( 'class' => 'headshot' ) );?>
</div>
Also, please note that the correct attribute for the `img` tag's URl is not `url`, it's `src`. | stackexchange-wordpress | {
"answer_score": 1,
"question_score": 0,
"tags": "php, images"
} |
Create custom API endpoint to change custom header image
My goal is to create a custom API endpoint that I can call with an API call that changes the custom header image in Wordpress to another image (which would be passed along the API call, or maybe just switch to another media file in Wordpress, or similar).
**_UPDATE:_** I have now found the set_theme_mod() function which seems to be what I'm looking for, but when I tried to implement it I couldn't quite get it to work. The API call seems to be setup correctly because when I call it, the current header image dissappears. The problem is though that the new image does not get set.
Big thanks in advance.
function cs_set_logo() {
set_theme_mod('header_image', $_POST['
return;
}
add_action('rest_api_init', function() {
register_rest_route('cs/v1', 'changelogo', [
'methods' => 'POST',
'callback' => 'cs_set_logo'
]);
}); | The header image falls under what WordPress calls **theme modification values.** To update that type of value, use the function `set_theme_mod()`
function cs_set_logo($request) {
set_theme_mod('header_image', $request->get_param('new_header_image'));
return new WP_REST_Response(null, 200);
}
add_action('rest_api_init', function() {
register_rest_route('cs/v1', 'changelogo', [
'methods' => 'POST',
'callback' => 'cs_set_logo'
])
}); | stackexchange-wordpress | {
"answer_score": 0,
"question_score": 0,
"tags": "php, functions, api, custom header, header image"
} |
Is it possible to have a template that works on multiple categories where the link address contains the specific category?
This question is for a very specific refinement on the use of WordPress template files. The refinement would work similarly to how default archive.php and variants work, but we would like to have a second template that has the same mechanism for querying the desired category through the link address.
The model is a wood site where some people like to browse through the default template style, but others would prefer to just see a list of links.
The goal is to create one template where the category would be passed to the template through the link, instead of having to create a new list template for each category. | Why not using a meta field ? That way you can determine which template to use for specific category template.
In your loop just get the current category that you are trying to load:
if( have_posts() ) {
while( have_posts() ) {
the_post();
$meta_value = get_post_meta( get_the_ID() , 'meta-field', true );
if($meta_value == 'template1') {
//I prefer using this method. Create folder templates with file content-template1.php where you can design your content. That way it is way more clear.
get_template_part('templates/content','template1');
// or you can use this method
the_title();
}
}
// Very Important
wp_reset_postdata();
} | stackexchange-wordpress | {
"answer_score": 1,
"question_score": 0,
"tags": "categories, templates, archive template"
} |
How do I register user without being authenticated
I get form data through ajax and I want to use it and add a new user with a subscriber role. to the original Wordpress users and also send them a notification about their account. Here is the bit of code that I have so far.
function set_form()
{
$fisrt_name = $_POST['fisrt_name'];
$email = $_POST['email'];
$email = $_POST['email'];
$admin =get_option('admin_email');
//Code to register user
die();
}
add_action('wp_ajax_set_form', 'set_form'); //execute when wp logged in
add_action('wp_ajax_nopriv_set_form', 'set_form'); //execute when logged out | You could use the wp_insert_user function to create the new user. And then with the wp_new_user_notification function you could send the notification. | stackexchange-wordpress | {
"answer_score": 0,
"question_score": 0,
"tags": "forms, user registration, notifications"
} |
Notify users only on post publish
I am using this function to notify users when their post is published. However, repeated emails are being sent when the post is updated. I only want to send 1 email when the post is published first and then not sent more emails if the post is subsequently updated.
function notifyauthor($post_id) {
$post = get_post($post_id);
$author = get_userdata($post->post_author);
$subject = "Post Published: ".$post->post_title."";
$message = "
Hi ".$author->display_name.",
Your post, \"".$post->post_title."\" has just been published.
View post: ".get_permalink( $post_id )."
"
;
wp_mail($author->user_email, $subject, $message);
}
add_action('publish_post', 'notifyauthor'); | You could use the `transition_post_status` hook instead, as it already knows what the current and previous status of the post are.
<?php
add_action('transition_post_status', 'wpse_366380_email_on_publish', 10, 3);
function wpse_366380_email_on_publish( $new_status, $old_status, $post ) {
// Only if this post was just published, and previously it was either
// "auto-draft" (brand new) or "pending" (not yet published)
if ( 'publish' == $new_status && ( 'auto-draft' == $old_status || 'pending' == $old_status ) ) {
$post = get_post($post_id);
$author = get_userdata($post->post_author);
$subject = "Post Published: ".$post->post_title."";
$message = "Hi ".$author->display_name.",
Your post, \"".$post->post_title."\" has just been published.
View post: ".get_permalink( $post_id )."";
wp_mail($author->user_email, $subject, $message);
}
}
?> | stackexchange-wordpress | {
"answer_score": 1,
"question_score": 0,
"tags": "php, functions, wp mail"
} |
Share or sync user table data with another user table
I have a software and a wordpress installed in the same database, there is a wordpress "user" table and the software "user_soft" table. Is there any way or plugin to sync the two tables so that when the user register in wordpress, automatically register in "user_soft"? | Welcome to WPSE. Asking for plugin recommendations is considered off-topic here, so here's an action approach to the problem.
`wp_insert_user()` takes care of adding new users to the database. The last action the function fires is `user_register`, which _"Fires immediately after a new user is registered"_. You could hook your function to this action and use it to update the custom DB table.
In your action function you can use the global `$wpdb` to manipulate your database tables whether they are standard WP tables or not. (You can also use `wpdb` class to connect to other databases, too.)
To insert new data into the database you can use the `wpdb::insert( string $table, array $data, array|string $format = null )` method.
If there's some user data that needs to be kept updated and synced, then you can hook to `profile_update` action, which `wp_insert_user()` also fires, but _"...immediately after an existing user is updated"_. | stackexchange-wordpress | {
"answer_score": 0,
"question_score": 0,
"tags": "plugins, users, mysql, table, sync"
} |
Border around menu button
I want the same effect than this post : < and I’m halfway there but can’t get the top border to be lower.
The page I need help with: <
Any help would be much appreciated.
Thanks. | Please add this CSS in your file. Remove all the CSS that you have added for "pricelist" class.
.pricelist a span{
border: 1px solid white;
padding: 12px;
}
.pricelist a span.plus{
border:0;
padding:0;
}
.pricelist a span .underline_dash{
display:none;
}
This CSS will make the nav as seen in the screenshot.
);
if ( $the_query->have_posts() ) :
while ( $the_query->have_posts() ) : $the_query->the_post();
the_title();
the_excerpt();
endwhile;
wp_reset_postdata();
else :
__('No post found');
endif; | stackexchange-wordpress | {
"answer_score": 1,
"question_score": 0,
"tags": "blog"
} |
How to create a plugin with automatic update?
I'm developing a plugin and would like to know how do I send automatic updates to it? Do I have to use webhooks for this?
The plugin will be for private use, it will scan the website to remove malware, however there is always the possibility of creating new malware outside of those that are already included in the removal list.
Thank you. | I think this plugin might help
< | stackexchange-wordpress | {
"answer_score": 0,
"question_score": 0,
"tags": "plugins, plugin development, woocommerce offtopic, automatic updates, virus"
} |
Order get_terms by count using a custom taxonomy hierarchy
When I test get_terms with normal Wordpress posts it seems to be working. Maybe because I don't have hierarchy yet for these categories. But it doesn't work with WooCommerces custom taxonomy "product_cat" when ordering by anything. Im trying to order by count and it returns them by name.
These product categories are nested 3 layers deep in the category tree. Maybe that effects it?
`$cats = get_terms(array( 'taxonomy' => 'product_cat', 'hide_empty' => false, 'orderby' => 'count', 'order' => 'DESC', 'number' => 5, )); echo '<pre>'; print_r($cats); echo '</pre>'; ` | Don't know if it's the best solution but I ended up using a custom query to show all categories ordered by count.
$cats = $wpdb->get_results("
select tt.term_id, count, name, slug
from ".$wpdb->prefix."term_taxonomy as tt
inner join ".$wpdb->prefix."terms as terms
on tt.term_id = terms.term_id
where taxonomy = 'product_cat'
order by count desc limit 10
");
echo '<pre>'; print_r($cats); echo '</pre>'; | stackexchange-wordpress | {
"answer_score": 0,
"question_score": 0,
"tags": "custom taxonomy, terms"
} |
Invisible spam post in backend
I do have a problem on my WordPress site. In the frontend there is a spam post (not a comment, a post) visible to everybody. I don't know where it comes from and all malware scans were negative so far. However, in order to solve this problem I will need to delete this post. But it can't be seen in the backend.
; ?>
</div>
Looking like this:
<
That white block at the bottom is just another div that follows.
The shortcode is not being recognised by the div and is displaying outside it. Not sure why this is.
thanks, | Maybe your form has a float property. So just add overflow hidden to parent div.
Take a look here: <
your code can be like that:
<div style="border: 3px solid green; margin-top: 1em; height: auto; overflow: hidden">
<h2>Blog notifications</h2>
<?php echo do_shortcode('[forminator_form id="9979"]'); ?>
</div> | stackexchange-wordpress | {
"answer_score": 1,
"question_score": 0,
"tags": "php, shortcode"
} |
WordPress and React how to integrate?
I am new to this. I am good at WordPress things but just wondering the possibilities with react integration. These are my doubts
1. If I develop a react app is it only possible to connect them via REST API? Is there is possibility deploy it as WordPress plugin.
2. I not sure, Gutenberg is created with react js? So is it possible to create a front form that allows adding adding custom post type with react js. I am aware of WordPress way but curious about the possibility with doing to it with react.
Please help. also if you have any reference links please let me know. | Check out Frontity, it's a React framework for integrating with WP <
However, if you want to build this I think you should be familiar with React and JSX | stackexchange-wordpress | {
"answer_score": 0,
"question_score": 0,
"tags": "rest api"
} |
How to add (and change the font of) the short product description to order page and customer's new order e-mail
I'd like to add the short product description to the e-mail that is sent to the customer when a new order is confirmed.
I've added the following via a code snippets plug-in:
add_filter( 'woocommerce_order_item_name', 'add_single_excerpt_to_order_item', 10, 3 );
function add_single_excerpt_to_order_item( $item_name, $item, $is_visible ){
$product_id = $item->get_product_id(); // Get the product Id
$excerpt = get_the_excerpt( $product_id ); // Get the short description
return $item_name . '<br><p class="item-description">' . $excerpt ; '</p>';
}
It is working correctly by adding the short description but now I would like to change the font type and size to match the rest of the e-mail.
Can you assist, please? | I don't know what the font is for the rest of the email but if you can discern that by examining one of the emails sent you'll want to copy the style rule to this element:
return $item_name . '<br><p class="item-description">' . $excerpt ; '</p>';
As this is an email you'll have to rely on fonts available to the user, so check the email and locate what fonts are being assigned and then add them like this:
return $item_name . '<br><p class="item-description" style="font-family:WHATEVERTHEFONTIS,Arial,Helvetica,sans-serif;font-size:XXpx;font-weight:XXpx;">' . $excerpt ; '</p>';
In earnest though, you'd be better off overriding the email templates using standard WooCommerce (I'm assuming this is for WooCommerce.) template overrides in your theme/child theme.
<
That will give you full control over the templates and rather than inline styling will allow you to update the actual `<style>` at the start of the email. | stackexchange-wordpress | {
"answer_score": 0,
"question_score": 0,
"tags": "woocommerce offtopic, templates, email, html email"
} |
How to show notice alert only on product dashboard page?
I want to remind to my plugin users that the plugin is enabled but only on `product` page (dashboard), i've came across the `$pagenow` global variable:
global $pagenow;
$pagenow != 'post.php'; // This will be shown on "normal posts" too
How can i add a notice alert only on product page? This is what i have at the moment:
add_action('admin_notices', function () {
if (!is_admin()) {
return;
}
$title = __e('Your plugin is enabled');
$div = '<div class="notice notice-info is-dismissible"><p>%s</p></div>';
$pluginPath = 'path-to/my-plugin.php';
if (is_plugin_active($pluginPath)) {
echo sprintf($div, $title);
}
}); | If you're on wp-admin/post.php, you've got either
* `global $post_type`
* or possibly `$_POST['post_type']`, if we don't have a post ID to look up the type from
that you can test for 'product'. See the first 50 lines of wp-admin/post.php.
As an aside, I don't think you need to check for is_admin in a admin_init handler; nor do you need to check if your plugin is enabled if this code is in the same plugin, since it won't be run unless the plugin is enabled. Unless you're testing for a different plugin that is. | stackexchange-wordpress | {
"answer_score": 1,
"question_score": 0,
"tags": "woocommerce offtopic"
} |
get_the_terms - only top level
This code works good:
$terms = get_the_terms(get_the_ID(), 'my_taxonomy');
if (!is_wp_error($terms) && !empty($terms)) {
foreach ($terms as $term) {
$name = $term->name;
$link = add_query_arg('fwp_typ', FWP()->helper->safe_value($term->slug), '
echo "<a href='$link'>$name</a><br />";
}
}
It generates:
* Term1 (first level - parent)
* Term2 (second level - child)
I would like to get only the first level terms. How to modify it? | Just have a quick test and seems both methods working well.
// @Rup's method
$terms = get_the_terms(get_the_ID(), 'my_taxonomy');
if (!is_wp_error($terms) && !empty($terms)) {
foreach ($terms as $term) {
// skip if parent > 0
if( $term->parent )
continue;
$name = $term->name;
$link = add_query_arg('fwp_typ', FWP()->helper->safe_value($term->slug), '
echo "<a href='$link'>$name</a><br />";
}
}
or
$terms = get_the_terms(get_the_ID(), 'my_taxonomy');
if (!is_wp_error($terms) && !empty($terms)) {
foreach ($terms as $term) {
// only do if parent is 0 (top most)
if( $term->parent == 0 ) {
$name = $term->name;
$link = add_query_arg('fwp_typ', FWP()->helper->safe_value($term->slug), '
echo "<a href='$link'>$name</a><br />";
}
}
} | stackexchange-wordpress | {
"answer_score": 2,
"question_score": 1,
"tags": "php, functions, custom taxonomy, terms"
} |
Use ACF Category Image for all Taxonomy Archive Views
I’m wondering if you could help with some code I’m struggling with.
I’ve got an ACF Image Field on the Post Category Taxonomy. I need to add it into the post loop so the category image shows up instead of the featured image. Here’s the code that I have in:
$current_term = get_queried_object();
$author_image = get_field('author_image', $current_term );
echo do_shortcode('[image_shortcode id="'.$author_image.'" image_size="original"]');
It’s working on the Category Archive page, but not on the Tags Archive page. Let me know your thoughts. | Thanks for your help Bob. I appreciate it. Your answer got me close, but I was able to figure this out. The actual answer ended up being this:
$post_categories = wp_get_post_categories( get_the_ID(), array('fields' => 'all'));
if ( $post_categories ) {
$current_term = $post_categories[0];
$author_image = get_field('author_image', $current_term );
echo do_shortcode('[image_shortcode id="'.$author_image.'" image_size="original"]');}
Thanks again. | stackexchange-wordpress | {
"answer_score": 0,
"question_score": 0,
"tags": "loop, taxonomy, advanced custom fields"
} |
Reverse order of posts in a certain taxonomy archive?
I have a custom post type `message` which has a custom taxonomy called `series`. Is there a way to reverse the date order of the posts in just that archive (oldest first)? I want to continue to show newest first in the basic all-messages archive as well as archives based on other taxonomies.
There are plenty of examples of how to do it for all archives, like this:
add_action('pre_get_posts', 'change_post_order');
function change_post_order($query){
$query->set('order','ASC');
$query->set('orderby','date');
}
But I don't know how to limit it to archives of just the `series` taxonomy. | Untested but can you do:
add_action('pre_get_posts', 'change_post_order');
function change_post_order($query){
if($query->is_tax('series')) {
$query->set('order','ASC');
$query->set('orderby','date');
}
}
Based of this and this. | stackexchange-wordpress | {
"answer_score": 1,
"question_score": 0,
"tags": "custom taxonomy, hooks, custom post type archives"
} |
Hide account tab to certain users
Hi there i was wondering if it was possible to hide the "Wholesale Ordering Form" to users who are not logged in as Wholesaler, we have made it so other user roles cannot access this section but preferably would want it to not display to regular customers at all. The account tab has been linked using a custom snippet provided by Wholesale Suite for WooCommerce Wholesale Order Form.
->roles)) {
// Your snippet here
}
This will only run the snippet that adds that tab when the user that is logged in has the wholesaler role. Be sure to replace `wholesaler` with whatever the slug of that role is on your website.
**Edit** :
If you want to check multiple arrays, you can just do this:
$roles = wp_get_current_user()->roles;
if(in_array('wholesaler', $roles) || in_array('administrator', $roles)) {
// Your snippet here
}
If you have more than two roles you want to check, here's an answer on how to check multiple values with in_array. | stackexchange-wordpress | {
"answer_score": -1,
"question_score": 1,
"tags": "woocommerce offtopic"
} |
How to give guest users "not logged in" a role?
I'm trying to give guest users "not logged in" a role.
I searched everywhere and I could not find a single solution that can make that happen. All what I found is to make an if statement in the `functions.php` file to give access to certain things, like for example post a comment without logging in.
However when there are a lot of roles it's hard to make it that way and it starts to be complicated.
Is there any way that I can achieve that?
Things that I have used
add_role( 'custom_role', 'Custom Role', array( 'read' => true ) );
and
<?php
global $user_login;
if( $user_login ) {
echo 'user logged in';
} else {
echo 'user not logged in';
}
?> | You need to add to the template directly or via a short code from PHP Snippets plugin.
Source: <
<?php
if ( is_user_logged_in() ) {
echo 'Welcome, registered user!';
} else {
echo 'Welcome, visitor!';
}
?> | stackexchange-wordpress | {
"answer_score": 0,
"question_score": 0,
"tags": "users"
} |
Wordpress is not able to change themes
Wordpress Website has two themes, newspaper magazine and twenty twenty, it uses by default newspaper magazine, if I change to twenty twenty, the homepage remains using newspaper magazine, but if I go to any other link or post, it uses twenty-twenty, also, the homepage remains the same no matter what changes I perform to it, even setting other pages to be the homepage. Not sure if this is a cache issue
Things I've done so far :
wp-rocket was being used and it was removed 3 days ago Cloudflare was used but was deactivated 3 days ago as well. I have cleared all browsers cache several times deactivated and activated all plugins Reinstall WordPress and themes | It is resolved now, it was caused by an .htaccess file placed in the uploads folder | stackexchange-wordpress | {
"answer_score": 1,
"question_score": 1,
"tags": "themes, cache, homepage"
} |
Get post and its children with WP_Query
I want the parent post _and_ its children posts. I don't know the parent post ID, only that its `post_password` field is not empty.
It's very similar to this question except the post ID is _not_ known in my case.
,
'post_type' => 'post'
// Add additional arguments
];
$q = new WP_Query( $args );
This code will get the parents post id when you are inside children post | stackexchange-wordpress | {
"answer_score": 1,
"question_score": 0,
"tags": "wp query, wp list pages"
} |
Redirect user to cart page when add to cart button is clicked
I am working on WooCommerce. When the user fills the detail and clicks on add to cart button, a user does not redirect to the cart button. A notification shows at the bottom “[NAME OF THE PRODUCT] has been added to your cart, View cart.” I want that if the user clicks on add to cart button after filling details, it should be redirected to the cart page automatically.
Here is screenshot < | In Woocommerce Settings Go to > Products, Tick Add to card behavior Redirect to the cart page
;
which is called between the password box and the 'remember me?' checkbox, and write out your hidden input field there, e.g.
function wpse_366921_hidden_login_field() {
?>
<input type="hidden" name="hidden-login-field" value="1" />
<?php
}
add_action( 'login_form', 'wpse_366921_hidden_login_field', 10, 0 ); | stackexchange-wordpress | {
"answer_score": 0,
"question_score": 0,
"tags": "plugins, plugin development"
} |
Multiple Address In WP-Option Value
I've tried to setup my wordpress using 1 domain name and 1 ip address, after this, all the css is missing, but the site still can be accessible using both domain and ip address.

;
define('WP_SITEURL', ' . $_SERVER['HTTP_HOST'] . '/' );
Now you can use Domain and IP together to access your wordpress. Of course you need to setup your webserver to listen to both
*It is not my VPN limitation though, just because I can and I think this is more cool. | stackexchange-wordpress | {
"answer_score": 0,
"question_score": 0,
"tags": "database, options, wp config"
} |
Why I don't see all my post in feed in Wordpress
I have a question. I want to get all my post but when I visit < I have only three post. In my website there are much more than three. How to update this file?
Kind regards | Please check your settings option, by going to **Settings > Reading** and check for number of items in **Syndication feeds show the most recent**. I have attached a screenshot of the option too.
This should fix the issue I guess. Do let us know.
:
RewriteRule ^article\.html$ - [R=404]
If this still results in an error, then try resetting the 404 error document (to the Apache default) before this:
ErrorDocument 404 default
You'll need to clear your browser cache to clear the cached (permanent) 301 redirect to the new URL. | stackexchange-wordpress | {
"answer_score": 1,
"question_score": 1,
"tags": "redirect, htaccess"
} |
Wordpress PWA with Form
Is it possible to use a form in a wordpress pwa. I am using the SuperPWA plugin and have a form on the site, the main focus on the site to collect data which is sent to google sheets..works fine. Will I be able capture data if the user is out of connectivity.
Ted | By default the service worker does not proxy (cache) POST requests so no, by design, it's not possible. However... More than one PWA do do just this. As one of the comments says, you need to contact the form plugin author for support.
Reference:
<
< | stackexchange-wordpress | {
"answer_score": 0,
"question_score": 0,
"tags": "plugins"
} |
How to use terms from the same custom taxonomy in different roles in a custom post type?
How can I use terms from the same custom taxonomy in different roles in a custom post type?
I am developing a genealogy site which includes among other things biographies of ancestors, presentations about ancestors / family history and old letters that the ancestors have sent to each other. To link all this up I have a custom taxonomy 'Ancestor' that I use to tag which ancestors are mentioned in which post/page.
To make the letters part more accessible, I have created a custom post type 'Letter'. Now I would like to assign one 'Ancestor' as a 'sender' and one as a 'recipient' to each 'letter'. | You could create two custom meta fields for your custom post type 'letter'. With the plugin Advanced Custom Fields, this can be done in a minute: <
With one field you choose your sender, with the other you chooce your receiver.
You can also create your fields by hand, but even the wordpress docs tell you that this plugins can be used: <
Meta Box Plugin: <
Picklist: <
Advanced Custom Fields: <
Advanced Custom Fields is awesome! It really gives you the tools to turn your wordpress page in an easy to use but complex content management system.
There are a lot of build in fuctions to use and methods to save data, get data, show data and hook into before save and much more. | stackexchange-wordpress | {
"answer_score": 0,
"question_score": 1,
"tags": "custom post types, custom taxonomy"
} |
get_user can't read variable
I have this little routine to find the user_id based on a usermeta field..
$scaleData = json_decode($reading, TRUE);
$deviceid = $scaleData["imei"];
echo $deviceid; // check to confirm is working. Yup
$WhoIsUser = get_users(
array(
'meta_key' => 'deviceid',
'meta_value' => '$deviceid'
)
);
$CurrentUser = $WhoIsUser[0]->ID;
echo $CurrentUser; //returns nothing
But if I switch 'meta_value' => 45455 (iow a known device number) it returns the ID no problem. I've tried both $deviceid and '$deviceid' What am I missing? | Needs double quotes
$WhoIsUser = get_users(
array(
'meta_key' => 'deviceid',
'meta_value' => "$deviceid"
)
); | stackexchange-wordpress | {
"answer_score": 0,
"question_score": 0,
"tags": "meta query, user meta"
} |
How to save a meta_value as a numeric value after I retrieve it via update_post_meta?
I tried things like $meta_rwp_user_score = (number_format_i18n($meta_rwp_user_score, 2)); , but this is not working. Where do I use that?
<?php
$meta_rwp_user_score['meta_rwp_user_score'] = get_post_meta(($anbieter_id),'rwp_user_score',true);
foreach ( $meta_rwp_user_score as $key => $value ) :
if ( 'revision' === $post->post_type ) {
return;
}
if ( get_post_meta( $postid, $key, false ) ) {
// If the custom field already has a value, update it.
update_post_meta( $postid, $key, $value );
} else {
// If the custom field doesn't have a value, add it.
add_post_meta( $postid, $key, $value);
}
if ( ! $value ) {
// Delete the meta key if there's no value
delete_post_meta( $postid, $key );
}
endforeach;
?> | According to the database schema, the `meta_value` is stored as `longtext`. It is probably because of generic purpose. So, to obtain a numeric value. There are 2 parts for doing so.
### Saving
Although it is storing as longtext, it is still good for preparing the rightful numeric format so that when retrieve it, it is likely to be expected value for conversion. So, for checking before saving, may use is_float() or is_numeric() and so on to make sure the storing value is expected.
### Retrieving
If the type float number is required to manipulate it correctly in the code after fetching the meta value from database. You may consider using php built-in function floatval() for float number to convert it before using. Another one is intval() for integer.
$meta_rwp_user_score['meta_rwp_user_score'] = floatval( get_post_meta(($anbieter_id),'rwp_user_score',true) );
// any text will be converted to 0
// manipulate as needed | stackexchange-wordpress | {
"answer_score": 0,
"question_score": 0,
"tags": "post meta, meta value"
} |
Redirect user to login before viewing custom post
I have a site with a listings page (< and all I'm trying to do is redirect a user who is not logged in to my login page (< before they can view an individual listing. If they are logged in then they can go straight to the individual listing.
I'd like to do this without having to use a plugin as this seems like it should be a relatively easy thing to do via php.
Thanks! | You could set up a child theme, and in the `single-listing.php` template, add conditions around the current code.
<?php
// If the user is not logged in, redirect
if ( false == is_user_logged_in() ) {
wp_redirect( wp_login_url() );
exit;
}
// Else the user is logged in; show the listing
else {
// Paste the regular template code here
}
?>
Everything else will remain public, while just the individual listings will force the user to be logged in before they can view the content. (This will also prevent search engines from seeing the content, so bear that in mind.) | stackexchange-wordpress | {
"answer_score": 1,
"question_score": 1,
"tags": "users, redirect, login, content restriction"
} |
Admin search not working for any type of post
Wordpress admin search is not working for any type posts i.e posts,pages,comments or any other custom posts.
Whenever trying to search for say string without quotes "my new post"** it always returns.
> Search results for ""
No matter what the search string is.
Also all of this error is on the pages related with edit.php | you can try writing something that appends to your query var when the search is initiated something as such as:
function gt_search_filter($query) {
global $wp_query;
if ($query->is_search)
if($_REQUEST['s']){
$wp_query->query_vars['s'] = $_REQUEST['s'];
}
return $query;
}
add_filter('pre_get_posts','gt_search_filter');
this worked for me but remember this is quite insecure and not advised what other thing you can do is adding more layers of filterations and everything before you finally give it to the query string. | stackexchange-wordpress | {
"answer_score": 1,
"question_score": 1,
"tags": "wp admin, search"
} |
How to embed HTML code from WP Coder plugin (or other) into Main Index Template of the theme
I want to add some custom HTML code on the home page of my school's website. I managed to do this by adding the HTML code into the Main Index Template (index.php) file of the theme, however the code is a bit messy and I would like to embed it from other file. I'm already using WP Coder, however when I try to add the [WP-Coder id="4"] part into the index.php file instead of showing the code as it should be it just shows this as a text and doesn't work.
Is there other way to link the Main Index Template page with WP Coder or other similar plugin. | You want to use the `do_shortcode()` function which allows the execution of shortcodes the same way that they run when used in the standard content areas.
<?php echo do_shortcode( '[WP-Coder id="4"]' ); ?>
If you need to get more complex you can read all about it here. | stackexchange-wordpress | {
"answer_score": 1,
"question_score": 1,
"tags": "plugins, customization, theme customizer"
} |
Why is WordPress showing local host ip address instead of domain name in url?
I am very new to Wordpress and I recently migrated my site after buying the domain name. While, I can look up my website with the url and it works fine, when I go into the wordpress back end, it the url shows < I have been stuck on this problem a long time and I would really appreciate if someone could help me. Thanks | You should define your website url in your wordpress config file ( in my case `/etc/wordpress/config-localhost.php` )
define('WP_SITEURL',' | stackexchange-wordpress | {
"answer_score": 0,
"question_score": 0,
"tags": "localhost"
} |
Is it possible to migrate a wordpress website to another wordpress account?
I have a website I developed on my own wordpress account and localhost. I uploaded this website on my clients hosting account using FTP. After uploading from localhost to live server, I am unable to login to wordpress using client's credentials it simply shows unknown username whereas when I log in using my credentials it shows my wordpress admin dashboard. I want to transfer my website frommy account to clients wordpress account. How do I do it? I'm relatively new to wordpress so sorry if it seems like a trivial question! | It is called either "Export and Import" or migration in Wordpress:
<
<
< | stackexchange-wordpress | {
"answer_score": 0,
"question_score": 0,
"tags": "migration"
} |
Subsets and Splits
No saved queries yet
Save your SQL queries to embed, download, and access them later. Queries will appear here once saved.