INSTRUCTION
stringlengths 11
999
| RESPONSE
stringlengths 0
999
| SOURCE
stringlengths 16
38
| METADATA
dict |
---|---|---|---|
get_next_posts_page_link adds Inexistent directories
Using get_next_posts_page_link function to get url of paginated post's next page url, but it's adding directories to it that simply do not exist.
Here is the code where I use it and probably missing something somewhere
while (have_posts()) : the_post();
the_content();
endwhile;
// echoing to see the actual url it would bring up if used in an anchor
echo get_next_posts_page_link();
And here are the urls
**On page 1:** mysitedomain.com/paginatedpage/page/2/ _instead of_ mysitedomain.com/paginatedpage/2/
**On page 2:** mysitedomain.com/paginatedpage/2/page/2/ _instead of_ mysitedomain.com/paginatedpage/3/
**On page 3:** mysitedomain.com/paginatedpage/3/page/2/ _instead of_ mysitedomain.com/paginatedpage/4/
And so on... | If you want links to the next and previous pages on a singular page created with `<!--nextpage-->` then you're using the wrong function.
`get_next_posts_page_link()`, as suggested by the name, is for getting the next page _of posts_ and is intended for use on archives.
To add the pagination links to a singular page, use `wp_link_pages()`, and use it inside the loop.
while (have_posts()) : the_post();
the_content();
wp_link_pages();
endwhile;
By default it outputs page numbers, but if you want "Next" and "Previous" links, set the `next_or_number` argument to `next`:
while (have_posts()) : the_post();
the_content();
wp_link_pages( array(
'next_or_number' => 'next',
) );
endwhile;
See the documentation for more options for customising the output. | stackexchange-wordpress | {
"answer_score": 0,
"question_score": 0,
"tags": "pagination"
} |
Instagram URL is converted into oEmbed
I have 8 Instagram URLs in this post out of which 3 are not converted into embed/iframes.
I'm using Gutenberg's Instagram embed blog to add the URL's.<
I see the block code in the classic editor which is same as other instagram blocks which render properly but for < it just returns URL.
<!-- wp:core-embed/instagram {"url":" -->
<figure class="wp-block-embed-instagram wp-block-embed is-type-rich is-provider-instagram">
<div class="wp-block-embed__wrapper">
</div>
</figure>
<!-- /wp:core-embed/instagram -->
I tried using shortcode also it's the same result only the below 3 Instagram posts don't render.
`[embed]
I need help debugging this weired issue
* <
* <
* < | Figured it out.
Embed shortcode stores the oemebd data as post meta using md5 hash.
wp-includes/class-wp-embed.php
// Check for a cached result (stored in the post meta)
$key_suffix = md5( $url . serialize( $attr ) );
$cachekey = '_oembed_' . $key_suffix;
$cachekey_time = '_oembed_time_' . $key_suffix;
And has a cache mechanism to fetch new data only after a day.
I deleted the post meta and then it started working. | stackexchange-wordpress | {
"answer_score": 2,
"question_score": 1,
"tags": "shortcode, embed, oembed, block editor"
} |
Trigger Customizer Publish (save) Action
Is there any way to trigger the Customizer's Publish button in javascript?
The use-case is to create a secondary save button within a section.
 | stackexchange-wordpress | {
"answer_score": 1,
"question_score": 0,
"tags": "customization, theme customizer"
} |
How to target a search result page?
I'am wondering how to target a search result page within the functions.php file in wordpress.
I know about "is_search" for the search page but what about the search result page ?
Can we put a condition with the query or something?
Thanks in advance.
All the best | > I'am wondering how to target a search result page within the functions.php file in wordpress.
Use `is_search`, and the `search.php` template
> I know about "is_search" for the search page but what about the search result page ?
They are the same thing, `is_search` indicates the main query is a search query. When `is_search` is true, WordPress loads `search.php` as the template, falling back to `archive.php` then `index.php` if they aren't present.
I'm not sure where the idea of a separate search page, and a separate search results page came from, but that's not how it works. There are search results, and a search form that can appear in any place, but no search page.
> Can we put a condition with the query or something?
If you want to modify the main query, use the `pre_get_posts` filter. This is true for all queries, not just search queries, and allows you to intercept the query parameters before WordPress fetches the posts to change what's fetched. | stackexchange-wordpress | {
"answer_score": 0,
"question_score": 0,
"tags": "conditional tags"
} |
custom css in admin panel by user id
I'm looking for adding a custom css in the admin panel by targeting user id cause I have another administrator but I want to hide something from him by css. I'm using this code to put some stylesheet files in the admin panel, but its for all users
add_action('admin_head', 'my_custom_fonts');
function my_custom_fonts() {
echo ' <link rel="stylesheet" type="text/css" href="../../admincss.css?v=1.3">';
} | done it
add_action('admin_head', 'my_custom_fonts');
function my_custom_fonts() {
global $current_user;
$user_id = get_current_user_id();
if(is_admin() && $user_id == '2'){
echo ' <link rel="stylesheet" type="text/css" href="../../new.css">';
}
} | stackexchange-wordpress | {
"answer_score": -1,
"question_score": 0,
"tags": "css, wp admin, admin css"
} |
How can I locate where the actions are defined?
Given the following code:
<form>
<h1> My form <h1>
<input type="text" />
<?php do_action( 'woocommerce_checkout_after_customer_details' ); ?>
</form>
How can I locate the "woocomerce_checkout_after_customer_details" defined?
It prints a button where I have to add functionality, maybe can I just use `add_action()` to add new features? in that case: how can I use `remove_action()` to stop rendering the old button?
Thanks in advance | You can find out what actions are assigned to given hook with this code:
function print_filters_for( $hook = '' ) {
global $wp_filter;
if( empty( $hook ) || ! array_key_exists( $hook, $wp_filter ) ) {
return;
}
print '<pre>';
print_r( $wp_filter[$hook] );
print '</pre>';
}
Call it where you need it. In your case:
<form>
<h1> My form <h1>
<input type="text" />
<?php do_action( 'woocommerce_checkout_after_customer_details' ); ?>
print_filters_for( 'woocommerce_checkout_after_customer_details' );
</form> | stackexchange-wordpress | {
"answer_score": 0,
"question_score": 0,
"tags": "woocommerce offtopic, actions"
} |
How to get correct value from checked()?
I am trying to create 2 raido buttons as a category custom field, and in function.php I do:
$feat = get_term_meta( $tag->term_id, '_feat', true );
<input name="feat" type="radio" value="0" <?php checked( '0' ); ?> />Si<br>
<input name="feat" type="radio" value="1" <?php checked( '1' ); ?> />No
And then I do
if ( isset( $_POST['feat'] ) )
update_term_meta( $_POST['tag_ID'], '_feat', $_POST['feat'] );
But I always get "No" as checked | The purpose of `checked()` is to output a `checked="checked"` attribute _based on a current value_. By using it the way you're using it there you're forcing `Si` to never be checked and `No` to always be checked.
So what you want to do is use both arguments of `checked()` to compare the value of the input to the current value:
<input name="feat" type="radio" value="0" <?php checked( $feat, '0' ); ?> />Si<br>
<input name="feat" type="radio" value="1" <?php checked( $feat, '1' ); ?> />No
With that change if `$feat` is `'0'` then the first checked will run, and if it's `'1'` the second will run. | stackexchange-wordpress | {
"answer_score": 2,
"question_score": 0,
"tags": "functions, custom field"
} |
How can the plugin directory path be returned into <script> </script>?
How can the plugin directory path be returned into `<script> </script>` instead of hard coding the path?
Here is the custom-page.php:
<?php get_header(); ?>
<script type="text/javascript" src="
<?php get_footer(); ?> | Take a look at this: <
plugins_url( "path/to/file", __FILE__ );
EDITED:
<script src="<?php echo plugins_url( "path/to/file", __FILE__ ); ?>"></script> | stackexchange-wordpress | {
"answer_score": 2,
"question_score": 1,
"tags": "php, pages, javascript"
} |
Custom admin plugin read CSV
I've made a plugin in admin, very simple. I just need to read a CSV files, put data into an array.
I use this :
$csv = array();
if (($file = fopen('my-file.csv', 'r')) === false){
echo 'There was an error loading the CSV file.';
}else{
while (($line = fgetcsv($file, 1000)) !== false){
$csv[] = $line;
}
fclose($handle);
}
I found this function on web, it works when I use it in a single php file on my local server (outside of wordpress).
The problem is I can't read the file. I put the file in the plugin directory.
I tried with many ways to link url but no one work.
Anyone know how I can read the file? | $_SERVER['DOCUMENT_ROOT'] should get you taken care of. Check this out:
<?php
echo 'Initializing Script...<br>';
$filepath = $_SERVER['DOCUMENT_ROOT']."/data/clients.csv";
echo "the file we seek:".$filepath."<br>";
$handle = fopen($filepath, "r") or die("Error opening file");
$i = 0;
while(($line = fgetcsv($handle)) !== FALSE) {
if($i == 0) {
$c = 0;
foreach($line as $col) {
$cols[$c] = $col;
$c++;
}
} else if($i > 0) {
$c = 0;
foreach($line as $col) {
$client_data[$i][$cols[$c]] = $col;
$c++;
}
}
$i++;
}
fclose($handle);
echo "inital loop good<br>";
echo "<pre>";
foreach ($client_data as $client_row){
$data = $client_row['column_header_label'];
//do whatever
}
?> | stackexchange-wordpress | {
"answer_score": 0,
"question_score": 0,
"tags": "plugins, plugin development"
} |
Filter oembeds tags to modify iframe attributes
By default, when putting another WP url inside a post/page, it oEmbeds it and produces a blockquote and iframe code with the default in the front-end:
<iframe class="wp-embedded-content" sandbox="allow-scripts" security="restricted" ....></iframe>
It also produces an error in the JS console `XMLHttpRequest cannot load No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin 'null' is therefore not allowed access.` which is hinting that it is blocking some scripts to run.
What is the best filter to use to modify the iframe produced in the front-end, for example, we want it to `allow-same-origin` attribute for `sandbox`
<iframe class="wp-embedded-content" sandbox="allow-scripts allow-same-origin" security="restricted" ....></iframe> | I was able to solve the the CORS issue by using this snippet which now allows this iFrame to `allow-same-origin` or runs scripts inside this domain.
function oembed_iframe_overrides($html, $url, $attr) {
if ( strpos( $html, "<iframe" ) !== false ) {
return str_replace('<iframe class="wp-embedded-content" sandbox="allow-scripts allow-same-origin"', '<iframe class="wp-embedded-content" sandbox', $html); }
else {
return $html;
}
}
add_filter( 'embed_oembed_html', 'oembed_iframe_overrides', 10, 3); | stackexchange-wordpress | {
"answer_score": 2,
"question_score": 2,
"tags": "filters, oembed"
} |
Make another copy of a plugin and install it
I'm trying to make another copy of this plugin SyncFields It contains just one file syncfields.php, So I tried to edit it and edit the functions with another name but it didn't work It appeared in the plugins page and activated it , but didn't find it in the menu I don't know what what did I missed | Most probably you haven't changed all IDs inside that plugin.
For example, when you register admin menu page, you have to pass its slug, which is unique identifier for that page. If you register two pages with the same slug, only one will be visible.
It's the same with registering options, custom post types, and so on...
So renaming only functions won't solve the problem... | stackexchange-wordpress | {
"answer_score": 0,
"question_score": 0,
"tags": "plugins, plugin development"
} |
Body class to each level of a hierarchical custom taxonomy
How would this be adapted to apply to specific custom taxonomies?
add_filter( 'body_class', 'custom_cat_archiev_class' );
function custom_cat_archiev_class( $classes ) {
if ( is_category() ) {
$cat = get_queried_object();
$ancestors = get_ancestors( $cat->term_id, 'category', 'taxonomy' );
$classes[] = 'catlevel-' . ( count( $ancestors ) + 1 );
}
return $classes;
} | Use `is_tax` instead of `is_category`, and update `get_ancestors` to get taxonomy from the queried object:
add_filter( 'body_class', 'custom_cat_archiev_class' );
function custom_cat_archiev_class( $classes ) {
if ( is_tax( ['custom_tax_1', 'custom_tax_2'] ) ) {
$term = get_queried_object();
$ancestors = get_ancestors( $term->term_id, $term->taxonomy, 'taxonomy' );
$classes[] = 'catlevel-' . ( count( $ancestors ) + 1 );
}
return $classes;
} | stackexchange-wordpress | {
"answer_score": 0,
"question_score": 0,
"tags": "custom taxonomy, css, body class"
} |
Move WooCommerce product tabs out of the tabs
I want to have the product tabs out of the tabs section and put them one down the other with no need of having the tabs functionality.
I can unset the tabs
add_filter( 'woocommerce_product_tabs', 'woo_remove_product_tabs', 98 );
function woo_remove_product_tabs( $tabs ) {
unset( $tabs['description'] );
unset( $tabs['reviews'] );
unset( $tabs['additional_information'] );
return $tabs;
}
but I dont know how to reset them in columns layout and not in tabs.
Thanks for any help | It turned out that `woocommerce_get_template()` was deprecated and replaced by `wc_get_template()`. I solved this by adding this to my `functions.php`.
add_action( 'woocommerce_after_single_product_summary', 'removing_product_tabs', 2 );
function removing_product_tabs(){
remove_action('woocommerce_after_single_product_summary','woocommerce_output_product_data_tabs', 10 );
add_action('woocommerce_after_single_product_summary','get_product_tab_templates_displayed', 10 );
}
function get_product_tab_templates_displayed() {
wc_get_template( 'single-product/tabs/description.php' );
wc_get_template( 'single-product/tabs/additional-information.php' );
comments_template();
} | stackexchange-wordpress | {
"answer_score": 2,
"question_score": 1,
"tags": "woocommerce offtopic, tabs"
} |
Show post content and title in diferent divs using WP_Query using a loop
im trying to display the post title and post content of posts in diferent divs using a loop to iterate the posts in $the_query, how can achieve this?
<?php $the_query = new WP_Query( 'posts_per_page=4' );?>
the structure should be something like this
<div class="grid">
<div class="main post">
<!--show data of the first post in the array-->
</div>
<div class="nested">
<div class="first post">
<!--show data of the second post in the array-->
</div>
<div class="second post">
<!--show data of the third post in the array-->
</div>
<div class="third post">
<!--show data of the fourth post in the array-->
</div>
</div> <!--end nested-->
</div> <!--end grid--> | PHP loops are loops - you can control them ;)
<?php
$the_query = new WP_Query( array('posts_per_page' => 4) );
if ( $the_query->have_posts() ) :
$the_query->the_post();
?>
<div class="grid">
<div class="main post">
<!--show data of the first post in the array-->
<?php the_title(); ?>
<?php the_content(); ?>
</div>
<div class="nested">
<?php while ( $the_query->have_posts() ) : $the_query->the_post(); ?>
<div class="post">
<!--show data of next post in the array-->
<?php the_title(); ?>
<?php the_content(); ?>
</div>
<?php endwhile; ?>
</div> <!--end nested-->
</div> <!--end grid-->
<?php endif; ?> | stackexchange-wordpress | {
"answer_score": 2,
"question_score": 0,
"tags": "posts, wp query"
} |
Static Page with php echo
I build a static page in my WordPress root folder. Now I'm trying to include a list of my categories with `echo clpr_categories_list();`.
Its not working because I some how have to tell the static page where to find my theme. How do I do this? Searched everywhere. | You need more than just telling the page where to find your theme. You will likely need to load WordPress.
You can do that with the following:
<?php
define('WP_USE_THEMES', false);
require('./wp-load.php');
?>
Is the `clpr_categories_list()` a theme function? You could just WP's `wp_list_categories()` function to what you need. The function accepts quite a number of arguments to customize the outpout. | stackexchange-wordpress | {
"answer_score": 0,
"question_score": 0,
"tags": "php, pages, static website"
} |
Unknow shortcode read on display site
I put the caption on a picture like this, the blog looks good,
` function for displaying the 'compact version' of the post content then this wouldn't appear. WordPress strips shortcodes out of post excerpts to prevent this happening.
If your theme is using its own method for generating the excerpt then its developer needs to fix the theme so that excerpts properly remove shortcodes. This can be achieved with the `strip_shortcodes()` function. | stackexchange-wordpress | {
"answer_score": 0,
"question_score": 0,
"tags": "shortcode, captions"
} |
How to create a wordpress widget that dynamically changes according to the page
I am creating a plugin in which my custom sidebar widget changes content depending on the page it is loading on. One way to do this is
// Register and load the widget
function custom_register_widget() {
register_widget( 'custom_widget' );
}
//trigger on every sidebar load
add_action('dynamic_sidebar', 'custom_register_widget' );
However, this calls the **register_widget()** on every page load ( thereby making changes to WordPress DB ), thus slowing the page speed.
Is there an efficient way to this? | `register_widget()` doesn't make any changes to the database. All it does is make a particular widget available to be used. It shouldn't be used on the `dynamic_sidebar` hook. It's supposed to be used on the `widgets_init` hook.
If you want the contents of a widget to change depending on the current page, then that logic needs to be in the widget itself, in the `widget()` method:
class My_Widget extends WP_Widget {
public function __construct() {}
public function widget( $args, $instance ) {
if ( is_page() ) {
$page_id = get_queried_object_id();
echo get_the_title( $page_id );
}
}
public function form( $instance ) {}
public function update( $new_instance, $old_instance ) {}
}
That example will output the current page title, if you're viewing a page. | stackexchange-wordpress | {
"answer_score": 1,
"question_score": 0,
"tags": "plugin development, widgets"
} |
How to hide a field of the editor by default
I am working on a blog with a pretty high number of authors. I want to keep them from accidentally sending a push message to our readers, since the button of the push-plugin we use looks dangerously similar to the "publish"-button.
Is there a way to hide an element like this push-button for certain user groups by default?
I can uncheck it in the view-menu above the editor, of course, but that doesn't change it for all other authors. | Here are a couple options.
You could just create a stylesheet that loads in the admin area, and enable that for certain users if needed. Here is an example of loading a stylesheet in the admin for users with the role of "shopmanager".
function my_admin_styles(){
$user = wp_get_current_user();
if( ! empty($user) && count(array_intersect(["shop_manager"], (array) $user->roles ))) {
wp_enqueue_style(
'admin_css',
get_stylesheet_directory_uri() . '/css/admin-shopmanager.css', array(), filemtime( get_stylesheet_directory() . '/css/admin-shopmanager.css')
);
}
}
add_action('admin_enqueue_scripts', 'my_admin_styles');
Then in your stylesheet add something like this...
#elementID {
display: none !important;
}
You might also try a plugin called "Capability Manager Enhanced" which allows you to disable things based on user role. | stackexchange-wordpress | {
"answer_score": 0,
"question_score": 0,
"tags": "editor"
} |
Filter default_content only for products
Is there any way to use `default_content` only for a certain post type, specifically `product` (WooCommerce)?
My code:
add_filter( 'default_content', 'set_default_content', 10, 2 );
function set_default_content( $content, $product ) {
$content ='content to add to a post']';
return $content;
}
I've tried with `if ( 'product' == get_post_type() )` or even `if ( 'page' == get_post_type() )` to test it but it's not working. | `default_content` is a filter used in the backend. You don't necessarily have anything in the loop so standard functions will probably fail. However, you're given a second argument of type `WP_Post`. You can check its `post_type` easily and work from there.
add_filter('default_content', 'WPSE_product_default_content', 10, 2);
function WPSE_product_default_content($post_content, $post) {
if ($post->post_type !== 'product')
return $post_content;
$content ='content to add to a post'
return $content;
} | stackexchange-wordpress | {
"answer_score": 1,
"question_score": 0,
"tags": "woocommerce offtopic, hooks, post content"
} |
A wordpress site keeps editing wp-content files after migration
We migrated our clients websites to a new server, just afterwards, a client started calling us upon problems with his website's layout and design (basically, all his wp-content/themes files are automatically updated).
I launched a backup restoration, and I noticed that the website gets back to normal just before the end of restoration.
But once restoration ended successfully, I see that the website's design is again changed.
So, to solve this, I did not check database restoration, which makes the site look normal for about 4 - 5 hours, and it deforms eventually after.
We scanned the website for malware, but in vain.
I don't think personally that it's a cache problem, since cache would not change files like `wp-content/themes/header.php` , whose PHP and HTML code get edited just after 4 - 5 hours.
Do you have an idea what may be the source of this problem?
Thank you | You may have an issue with parent/child theme overwriting like Jacob Peattie said in the comments.
Another possibility is that your hosting provider is changing something during that restore process. Check your wp-config.php settings to make sure they haven't changed, and check your Settings > General tab in wp-admin to make sure your domain hasn't changed. The WordPress Address (URL) and the Site Address (URL). I know of a few hosting providers who try to convert the site's domain when migrating and restoring backups, and if you have a custom domain setup and this changes from its original value, then your site doesn't know how to find the theme content that is hard linked and located in wp-content. Any relative links would still work if the base domain changed, but any hard links would have been broken. (This might be hard to check if you don't have access to any root files) | stackexchange-wordpress | {
"answer_score": 1,
"question_score": 0,
"tags": "themes"
} |
when contact form7 submited domain redirects to example.com means (example domain)
When contact form7 is submitted the domain redirects to Example Domain. Here is the image  {
location = '
}, false );
</script> | stackexchange-wordpress | {
"answer_score": 0,
"question_score": 0,
"tags": "redirect, plugin contact form 7"
} |
Wrong domain in uploads folder
I just changed my website's domain and the user profile pictures saved in `wp-content/uploads/...` still have the old domain in the url. Example:
`
And i want to change them all to
`
How can I do this?
Thank you! | I will allow myself to expand on Ricks answer as there are a few ways to change old domain to new domain and each might be helpful depending on your situation.
1) use the **Better Search and Replace plugin** < plugin as suggested in the answer above.
2) use **Database Search and Replace script** <
You can easily upload it to your server via FTP and then delete once you replace the domain names.
It does not require WordPress to run just PHP and MySQL (so this can be plus or minus depending on your use case i suppose).
3) if you have access to **WP CLI (WordPress command line interface)** you can use the `wp search-replace` command to update the domain <
With WP CLI installed on your server already, this is the quickest way to do that i think and does not require installing anything.
4) do it manually in the database, but with so many tools available i would recommend selecting a solution from #1 to #3. | stackexchange-wordpress | {
"answer_score": 2,
"question_score": 1,
"tags": "images"
} |
WP Query - Posts Per Page not working in combination with category__in
I'm not sure whether it's a bug or i'm doing something wrong, but it doesn't seem like `posts_per_page` works at all when using `category__in`.
My query is below, even though I've set `posts_per_page` to `1`, it's still showing all posts.
$posts = new WP_Query(array(
'post_type' => 'post',
'category__in' => wp_get_post_categories($post->ID),
'posts_per_page' => 1,
'post__not_in' => array($post->ID)
));
Any ideas? | i am testing your code on my dev site and it returns only 1 result (although there are 3 items in the same category), so your code seems to be fine, maybe there is some other filter applied which ignores the posts_per_page param.
You can try using `suppress_filters => true` param in your WP_Query args list or use the get_posts() function instead of WP_Query as the function has supress_filters enabled by default so the code would be
` $posts = get_posts(array( 'post_type' => 'post', 'category__in' => wp_get_post_categories($post->ID), 'posts_per_page' => 1, 'post__not_in' => array($post->ID) )); `
Hope this helps. | stackexchange-wordpress | {
"answer_score": 0,
"question_score": 1,
"tags": "posts, wp query, loop"
} |
How to add Woocomrce cart page shipping calculator to my country state list
Im beginner for the word press , I don't know if the issue is because of the . The problem is that the "calculate shipping" option on my cart page doesn't allow users to select my country / state list, only allowed postal code
i want to know How to add Woocomrce cart page shipping calculator to my country state list, reason my country state list not here
example
;
add_filter('woocommerce_countries_allowed_country_states','sa_woocommerce_state');
function SA_woocommerce_states( $states ) {
$states['ZA']['EC'] = __('Eastern Cape', 'woocommerce');
return $states;
} | stackexchange-wordpress | {
"answer_score": 1,
"question_score": 0,
"tags": "woocommerce offtopic"
} |
Get rid of the word private in bbpress forums names
When I declare a forum private the word "private:" is prepend to the title of the forum, and is visible even for the register members.
how can I get rid of that prepend word? | AFAIR BBPress relies on WP functions with these titles, so most probably this will be helpful:
function remove_private_prefix_from_title( $title ) {
return '%s';
}
add_filter( 'private_title_format', 'remove_private_prefix_from_title' );
And here you can find docs for that filter: `private_title_format` | stackexchange-wordpress | {
"answer_score": 0,
"question_score": 0,
"tags": "bbpress, forum"
} |
How to recognize which plugin generated this code?
I just took over a website created with wordpress but is broken, the hosting provider reinstalled wordpress but kept the database, so all the information is there, however i can see that the code for the pages seems to have been generated by using some plugin or similar, so now I don't have information of which plugins were installed before but i do have pages that display this kind of code:
[section__dd class= 'inhale-top inhale-bottom'][column_dd span='12'][text_dd]
does anyone recognize it and knows which plugin was it so i can restore the site or at least see some pages as they were before? I'm usually just in charge of hosting and db management not really familiar with plugins | I found the plugin by running a search for the string "text_dd" in the `wp-content/plugins/` directory.
Looks like this specific plugin (which provides `text_dd`, `column_dd` and `section_dd` shortcodes) is called "dnd-shortcodes" and contains the following snippet of information:
Plugin Name: Drag and Drop Shortcodes
Plugin URI:
Description: Visual drag and drop page builder containing great collection of animated shortcodes with paralax effects and video backgrounds
Version: 1.2.2
Author: Abdev
Author URI: | stackexchange-wordpress | {
"answer_score": 1,
"question_score": -1,
"tags": "plugins"
} |
wooCommerce checkout page State / County (optional) validate not working
wooCommerce checkout page **State / County (optional)** validate not working
that is my added code
add_filter(‘thwcfd_State_field_override_required’,’__return_true’);
any idea for how to add mandatory for the **State / County (optional)**
like as `State / County (optional)*`
look my issue
. It could works.
add_filter( 'woocommerce_billing_fields', 'woo_filter_state_billing', 10, 1 );
function woo_filter_state_billing( $address_fields ) {
$address_fields['billing_state']['required'] = true;
return $address_fields;
}
add_filter( 'woocommerce_shipping_fields', 'woo_filter_state_shipping', 10, 1 );
function woo_filter_state_shipping( $address_fields ) {
$address_fields['shipping_state']['required'] = true;
return $address_fields;
} | stackexchange-wordpress | {
"answer_score": 1,
"question_score": 1,
"tags": "woocommerce offtopic, validation"
} |
Add custom variable in Contact Form 7 mail body
I set cookie for my users to know from which source they come to the site and I want when user contact us their message comes with their cookie as well.
So that I created a new shortcode and added in mail section but it mails direct shortcode not its returned value
Code :
function my_shortcode( $atts ) {
return isset($_COOKIE['my_source']) ? $_COOKIE['my_source'] : '' ;
}
add_shortcode( 'my-source', 'my_shortcode' );
**Message body in contact form 7 :**
Name : [your-name]
Email : [your-email]
Phone : [form-tel]
My Source : [my-source]
**Email I Received :**
Name : Mohit Bumb
Email : [email protected]
Phone : 19191919191
My Source : [my-source] | You should do it like so:
add_action( 'wpcf7_init', 'custom_add_form_tag_my_source' );
function custom_add_form_tag_my_source() {
// "my-source" is the type of the form-tag
wpcf7_add_form_tag( 'my-source', 'custom_my_source_form_tag_handler' );
}
function custom_my_source_form_tag_handler( $tag ) {
return isset( $_COOKIE['my_source'] ) ? $_COOKIE['my_source'] : '';
}
See the documentation for more details.
Or you can also try this, to parse regular shortcodes:
add_filter( 'wpcf7_mail_components', function( $components ){
$components['body'] = do_shortcode( $components['body'] );
return $components;
} ); | stackexchange-wordpress | {
"answer_score": 2,
"question_score": 2,
"tags": "plugins, shortcode, plugin contact form 7"
} |
Max file size not updating
Hi I am a beginner at WordPress and am currently trying to increase my file upload size.
So far I've tried two ways:
The first way was to add this to the bottom of the functions.php file:
@ini_set( 'upload_max_filesize' , '64M' );
@ini_set( 'post_max_size', '64M');
@ini_set( 'max_execution_time', '300' );
That didn't seem to work.
The second way I tried was to install the PHP Settings plugin and add this to the file
upload_max_filesize = 64M
post_max_size = 64M
max_execution_time = 300
However, when I try to verify that my change updated by clicking on `Media > Add New`, I still see 8MB as the max file size:
;
function override_default_address_checkout_fields( $address_fields ) {
$address_fields['billing_first_name']['placeholder'] = 'Enter your first name';
$address_fields['billing_last_name']['placeholder'] = 'Enter your last name';
return $address_fields;
} | Add the code in your themes `functions.php`.
add_filter( 'woocommerce_checkout_fields' , 'override_billing_checkout_fields', 20, 1 );
function override_billing_checkout_fields( $fields ) {
$fields['billing']['billing_first_name']['placeholder'] = 'Enter First Name';
$fields['billing']['billing_last_name']['placeholder'] = 'Enter Last Name';
return $fields;
}
Solved by adding the code in this way | stackexchange-wordpress | {
"answer_score": 1,
"question_score": -1,
"tags": "php, woocommerce offtopic, pluggable"
} |
Detect if Cron is Running
Many times I have code and I want to make sure it only runs in a cron context, or it never runs in a cron context.
Is there an `is_cron_running` style function? | Yes, `wp_doing_cron` will return true if the current request is a WP Cron request, or if it's triggered from WP CLI
< | stackexchange-wordpress | {
"answer_score": 2,
"question_score": 1,
"tags": "wp cron, cron"
} |
Adding id and class to the search input in WordPress search form
I want to apply the AJAX feature to the WordPress custom theme for search. And I need to target the input using id and class.
I didn't find any tutorial on adding id to the premade WordPress search form. Remember you, I am talking about the **get_search_form()** function.
I want to modify its input and want to add class to it. How can I do that whether using `add_filter` or anything else. Thanks in advance. | You can hook into the `get_search_form()`. Set the priority high enough to override anything created in a theme. If you do have searchform.php in your theme, it will be used instead. The input text field should be named s and you should always include a label like in the examples below.
WordPress Search Form Function Track
function custom_search_form( $form ) {
$form = '<form role="search" method="get" id="searchform" class="searchform" action="' . home_url( '/' ) . '" >
<div class="custom-search-form"><label class="screen-reader-text" for="s">' . __( 'Search:' ) . '</label>
<input type="text" value="' . get_search_query() . '" name="s" id="s" />
<input type="submit" id="searchsubmit" value="'. esc_attr__( 'Search' ) .'" />
</div>
</form>';
return $form;
}
add_filter( 'get_search_form', 'custom_search_form', 100 ); | stackexchange-wordpress | {
"answer_score": 3,
"question_score": 1,
"tags": "filters, search"
} |
Update PHP version 5.3 to 7.2 or first WP 4.7.11 to 4.9.8?
I am not sure if I am better of by upgrading WP to 4.9.8 when my PHP version is still on 5.3 or do the other way? | You should update both. ASAP.
PHP 5.3 us not supported for over 3 years... So it may have security vulnerabilities...
AFAIR there are no known vulnerabilities in WP 4.7.11, but... It's an old version too...
WP 4.7.11 should work fine on PHP 7.2 and WP 4.9.8 should also work on PHP 5.3 (but at least 5.6 is recommended).
So I would go with updating PHP first and then WP. | stackexchange-wordpress | {
"answer_score": 3,
"question_score": 1,
"tags": "php, upgrade"
} |
How to restrict access to a page?
I am developing a page in WordPress. In `functions.php` file I have this:
function feed_add_notmusa() {
add_feed('mypage', 'mypage_function');
}
function mypage_function() {
get_template_part('/mypage');
}
But how can I restrict access to `/mypage` so only logged in users can access?
Could you please help me? | Try this: is_user_logged_in
function mypage_function() {
if( is_user_logged_in() ) {
get_template_part('mypage');
}else{
echo 'please login for awesomeness';
}
} | stackexchange-wordpress | {
"answer_score": 1,
"question_score": 0,
"tags": "user access"
} |
Seeking specific Wordpress Layout
I this is the correct place to ask this question. I am seeking a WordPress theme that looks similar to this site <
I really like the effect of the moving containers in the background. I searched through ThemeForest but can not find anything comparable.
Does anybody know a theme that looks like this? Free or paid doesn't matter. | It's a custom theme made specifically for this company. The effect you are looking for is called Parallax Scrolling. More info can be found here (example javascript plugin): <
Also, when looking into Themes, make sure to check this: < | stackexchange-wordpress | {
"answer_score": 0,
"question_score": 0,
"tags": "plugins, themes, design"
} |
wordpress sites saved as apps rather than links when using iphone "add to home screen"
When using "add to home screen" in ios safari, the wordpress sites I build for my clients are being saved as discreet apps rather than links that open in the browser. I tap the newly created icon, and the site opens as an app rather than a new tab in mobile safari (my default browser).
This seems to be semi recent behavior. Maybe in the past 2 years at the most. I've tested a number of sites, and it seems to only happen on the WP sites I've built within the past 2 years max. Other sites are saved to the home screen as browser links. Has anyone encountered this before and know how to stop it from happening? | An online favicon generator that I use included a site.webmanifest file. In that file I needed to change this...
"display": "standalone"
...to this:
"display": "browser" | stackexchange-wordpress | {
"answer_score": 1,
"question_score": 0,
"tags": "iphone"
} |
What's the difference between "parent" and "category_parent" in a WP_Term object?
What's the difference between "parent" and "category_parent" in a WP_Term object? For example:
[1] => WP_Term Object
(
[term_id] => 24
[name] => Essential Oils
[slug] => essential-oils
[term_group] => 0
[term_taxonomy_id] => 24
[taxonomy] => category
[description] =>
[parent] => 22
[count] => 14
[filter] => raw
[cat_ID] => 24
[category_count] => 14
[category_description] =>
[cat_name] => Essential Oils
[category_nicename] => essential-oils
[category_parent] => 22
) | The properties prefixed with `category_` or `cat_` are there for backwards compatibility.
Taxonomies and terms were introduced in WordPress 2.3 (11 years ago) and categories were converted into a taxonomy at that time. Prior to this categories had their own properties (the ones with the aforementioned prefixes).
For backwards compatibility, the `_make_cat_compat()` function is used in some places to add the old properties to categories. You can see from the source that all it does is copy the standard term properties to the old names, so `parent` and `category_parent` will always have the same value, as an example.
In 2018 you should avoid using the category-specific properties. | stackexchange-wordpress | {
"answer_score": 1,
"question_score": 2,
"tags": "categories, taxonomy"
} |
Adding orderby url parameter to main CPT admin menu link
Is it possible to change the main admin menu link for a CPT (the link to edit.php) to include URL parameters?
I wan't to make the posts list default to sorting by "title" but I don't like how updating the main query to force a "default" order doesn't set column header to reflect it.
If you click on the "Title" column header it adds the "orderby" url parameter so I'm wondering if there is a hook/filter that would allow me to append this to the menu link.
I can't see how this could be done when registering the new post type and would prefer not to use javascript to add it on after the page has loaded. | You can set `$_GET` directly inside your `pre_get_posts` action to get the UI to pickup that change:
function wpd_test_pre_get( $query ) {
// put whatever conditions to target your cpt here
if( is_admin() && $query->is_main_query() ){
// modify query
$query->set('orderby', 'title');
$query->set('order', 'asc');
// set $_GET vars
$_GET['orderby'] = 'title';
$_GET['order'] = 'asc';
}
}
add_action( 'pre_get_posts', 'wpd_test_pre_get' ); | stackexchange-wordpress | {
"answer_score": 0,
"question_score": 0,
"tags": "custom post types, admin"
} |
How to display a sitmap horizontally?
I've created a sitemap successfully using wp Realtime sitemap. I've read their instructions and made pages. but i want to show this sitemap horizontally which i attached .I created this sitemap using wp-realtime-sitemap plugin.Can anyone suggest me some plugins for doing sitemap horizontally? , until when is it considered safe to postpone the 5.x upgrade and keep projects running in 4.x? | As stated here:
> The only current officially supported version is WordPress 4.9.8. Previous major releases before this may or may not get security updates as serious exploits are discovered.
And it has always been that way - only one version is officially supported.
This means it's always a bad idea to postpone updates.
So if you're afraid of Gutenberg, then you should:
1. Prepare a test version for your site and check if it will cause any problems with 5.0.
2. Disable Gutenberg, if you don't want to use it.
You can disable Gutenberg with this code:
if (version_compare($GLOBALS['wp_version'], '5.0-beta', '>')) {
// WP > 5 beta
add_filter('use_block_editor_for_post_type', '__return_false', 100);
} else {
// WP < 5 beta
add_filter('gutenberg_can_edit_post_type', '__return_false');
}
or using one of available plugins. | stackexchange-wordpress | {
"answer_score": 3,
"question_score": 1,
"tags": "plugins, themes, upgrade"
} |
404 on internal pages, in all sites in my local server
I have a local Apache server, **with module rewrite loaded** , all my Wordpress files in this server fail to find internal pages whenever permalinks options are set to something different than _simple_.
Setting permalinks options to anything different or saving changes to force _.htaccess_ to refresh, as many answers suggest, is not working in this case.
_.htaccess_ has **777** file permissions.
This is the list of loaded modules in Apache:
> core mod_so mod_watchdog http_core mod_log_config mod_logio mod_version mod_unixd mod_access_compat mod_alias mod_auth_basic mod_authn_core mod_authn_file mod_authz_core mod_authz_host mod_authz_user mod_autoindex mod_deflate mod_dir mod_env mod_filter mod_mime prefork mod_negotiation mod_php7 mod_reqtimeout mod_rewrite mod_setenvif mod_status mod_xsendfile | This can be related to your overall Apache configuration and have nothing to do with WordPress itself. By default, Apache will not load any custom _.htaccess_ files, you need to set `AllowOverride` for the given directory like so
<Directory /path/to/site>
AllowOverride FileInfo
# etc
</Directory>
`FileInfo` should suffice, if not, try `All` and check the official documentation. | stackexchange-wordpress | {
"answer_score": 1,
"question_score": 0,
"tags": "permalinks, 404 error"
} |
Unable to delete option
I am able to delete the option with form action `admin-post.php` but it gives me a blank page after clicking the button
<form action="<?php echo admin_url('admin-post.php'); ?>" method="post">
<input type="hidden" name="action" value="my_media_update">
<input type="submit" value="Update Media Titles and ALT Text">
</form>
public function kh_update_media_seo() {
delete_option('myoption');
}
add_action( 'admin_post_my_media_update', 'kh_update_media_seo' );
if I change the `action ="admin_url('admin.php?page=mycustomoptionspage');"` it redirects to my original page but does not delete the option -> `delete_option('myoption')` | You're almost there... If you send the request to `admin-post.php`, then only your callback will print the response. And since your callback doesn't print anything, then you're getting blank screen.
Most of the time what you want to do is to perform a redirect inside such callback:
public function kh_update_media_seo() {
delete_option('myoption');
wp_redirect( admin_url('admin.php?page=mycustomoptionspage') );
exit;
}
add_action( 'admin_post_my_media_update', 'kh_update_media_seo' ); | stackexchange-wordpress | {
"answer_score": 0,
"question_score": 0,
"tags": "theme development, forms, options"
} |
WP All import sale price 0
I want to import woocommerce products from an xml file, i got a problem, with the sale price. In the provided xml some products sale price is “0,00”.
I would like to skip theese cases, and import the sale price only to products what have a real sale price. | You can use an IF statement like this to import a blank value in the case that the real value is “0,00”:
[IF({saleprice[1][.="0,00"]})][ELSE]. {saleprice[1]}[ENDIF]
Just be sure to change “saleprice” to the correct element name from your file. | stackexchange-wordpress | {
"answer_score": 0,
"question_score": 0,
"tags": "woocommerce offtopic, xml"
} |
Author name length character limit?
In comments, I want to limit author names. For example, the author's name should be no more than 10 characters. I'm looking for a way to do this. Thank you very much in advance. | There's a filter called `get_comment_author` that you can hook into to modify a comment author's appearance.
add_filter( 'get_comment_author', function( $author, $comment_id, $comment ) {
// limit to first 10 characters
$author = substr( $author, 0, 10 );
return $author;
}, 10, 3 ); | stackexchange-wordpress | {
"answer_score": 0,
"question_score": 0,
"tags": "comments, author, comment form, username, characters"
} |
How do I create a custom partial / template?
I have created an sign up form and placed it in my header:
<div>
<h5 class="myapp-sign-up-text">Sign up for updates</h5>
<form class="myapp-email-form">
<input type="text" name="email" placeholder="Your email address" class="myapp-subscription-input" />
<input type="submit" value="Subscribe" class="myapp-subscription-submit" />
</form>
</div>
I would like to use the same code for my footer. Is there a DRY way of putting this into a partial and loading it using a PHP function? | The thing you're searching for is `get_template_part` function.
So let's say you put your form in file called `part-form-signup.php`. Then you can easily include that partial template anywhere using:
get_template_part( 'part-form-signup' ); | stackexchange-wordpress | {
"answer_score": 2,
"question_score": 1,
"tags": "theme development, templates"
} |
Detect what link user clicks and Redirect to a specific page for logged in users only
I have a link in my WP website Account link. I would like this to work normally for logged out users. However for Logged-in users i would like this link to take them to another page url.
I have tried:
function my_logged_in_redirect_sub() {
if ( is_user_logged_in() &&($_GET['account'] )
) {
wp_redirect( get_permalink( 15498 ) );//the redirect page id
die;
}
}
add_action( 'template_redirect', 'my_logged_in_redirect_sub' );
The $_GET['url'] doesn't work
**Question** : How can i target a specific URL with PHP? | Here are 2 examples which you will need to modify slightly to get it working for your specific needs.
add_action( 'admin_init', 'redirect_non_logged_users_to_specific_page' );
function redirect_non_logged_users_to_specific_page() {
if ( !is_user_logged_in() && is_page('add page slug or ID here') && $_SERVER['PHP_SELF'] != '/wp-admin/admin-ajax.php' ) {
wp_redirect( ' );
exit;
}
}
Put this in your child theme functions file, change the page ID or slug and the redirect url.
You could also use code like this:
add_action( 'template_redirect', 'redirect_to_specific_page' );
function redirect_to_specific_page() {
if ( is_page('slug') && ! is_user_logged_in() ) {
wp_redirect( ' 301 );
exit;
}
}
You can add the message directly to the page or if you want to display the message for all non logged in users, add it to the code.
< | stackexchange-wordpress | {
"answer_score": 0,
"question_score": 0,
"tags": "php, functions, wp redirect"
} |
Backbone event attachment:compat:ready can't hook
I want to ask question about events in backbone. I have problem to run some function when hook is triggerd.
I want to
wp.media.view.AttachmentCompat.prototype .on("attachment:compat:ready", function (e) {
console.log("READYY");
});
But this isn't working. What object handle the events of AttachmentCompat ? Maybe i do it to early ?
I was able to run my function by extending , but for me isn't best way.
var AttachmentCompatNew = wp.media.view.AttachmentCompat.extend({
postSave: function () {
this.controller.trigger('attachment:compat:ready', ['ready']);
}
});
wp.media.view.AttachmentCompat.prototype = AttachmentCompatNew.prototype;
Can some one help me to understand how i can trigger my functions on diffrent events ?? | if (wp.media) {
wp.media.view.AttachmentCompat.prototype.on("ready", function (e) {
console.log("Kompat Ready mokor 12");
});
}
This event name is "ready" :) works now fine . Maybe this will help someone. | stackexchange-wordpress | {
"answer_score": 1,
"question_score": 1,
"tags": "plugin development, backbone"
} |
Disable theme WooCommerce template
Just purchased a premium WooCommerce-read theme. Unfortunately, this theme comes with a /woocommerce folder. How can I disable this templates,without deleting whole folder? | Many themes overwrite WooCommerce template files. A behaviour that can cause malfunctions.
WC_TEMPLATE_DEBUG_MODE will prevent overrides in themes from taking priority
// Add this to wp-config.php file
define( 'WC_TEMPLATE_DEBUG_MODE', true );
< | stackexchange-wordpress | {
"answer_score": 0,
"question_score": 0,
"tags": "woocommerce offtopic, templates, wp config"
} |
Where to write custom logs in WordPress
I am creating a plugin in WordPress, the plugin creates logs for some events, my question is where should I write custom logs, so that no explicit file read/write permission required. I am looking to put logs at one of below two locations-
1\. wp-content/plugins/pluginName/logs
2\. wp-content/logs | Any files you want to create, such as logs, should be created in the `wp-content/uploads/` directory. Probably in your own subdirectory. This is because this is directory will be the most reliably writable, since it needs to be writable for everyday usage (for uploading media).
You can use `wp_upload_dir()` to get the path to the uploads directory, and `mkdir()` to create a directory there:
$uploads = wp_upload_dir( null, false );
$logs_dir = $uploads['basedir'] . '/pluginName-logs';
if ( ! is_dir( $logs_dir ) ) {
mkdir( $logs_dir, 0755, true );
}
$file = fopen( $logs_dir . '/' . 'log.log', 'w' );
`wp-content` would be the next option, but I don't see any reason to prefer it over the uploads directory. Definitely don't put it inside your plugin directory. If you did you would lose any logs whenever the plugin is updated. | stackexchange-wordpress | {
"answer_score": 0,
"question_score": 2,
"tags": "plugin development, wp filesystem"
} |
Change Featured Image / Thumbnail CMS Description
I'd like to be able to edit the description/help text that appears beneath the field in the CMS page editor for a custom post type.
I know I can change the name and button/link text by passing items into the `labels` array in register post type.
'featured_image' => __('Foo'),
'set_featured_image' => __('Set Foo'),
'remove_featured_image' => __('Remove Foo'),
'use_featured_image' => __('Use as Foo')
But is there a way to add to edit the help text that displays beneath the field? It says "Click the image to edit or update" if an image is selected. I'd like to add further instructions as to precisely what kind of image to use.
Ideally this text should appear before an image is selected as well as after. But I'd settle for being able to edit the text that shows after. | @RiddleMeThis got me pointed in the right direction, but I needed it to only apply to a single post type so this is my solution:
add_filter('admin_post_thumbnail_html', function ($content) {
global $pagenow;
$isNewFoo = 'post-new.php' === $pagenow && isset($_GET['post_type']) && $_GET['post_type'] === 'foo';
$isEditFoo = 'post.php' === $pagenow && isset($_GET['post']) && get_post_type($_GET['post']) === 'foo';
if ($isNewFoo || $isEditFoo) {get_post_type($_GET['post']) === 'foo') {
return '<p>' . __('Your custom text goes here') . '</p>' . $content;
}
return $content;
}); | stackexchange-wordpress | {
"answer_score": 0,
"question_score": 1,
"tags": "custom post types, post thumbnails"
} |
Conditional: IF post creation date is in the first half OR last half of the year
I'm trying to find a way how to have a simple conditional whereby I can echo something depending on whether the post date is in the first half or last half of the post date year. | I found this elsewhere and it worked for me...
if( (int)get_the_time( 'm' ) <= 6 ) {
echo 'Some time between January and June.';
} else {
echo 'Some time between July and December.';
} | stackexchange-wordpress | {
"answer_score": 0,
"question_score": 0,
"tags": "date, conditional content"
} |
where should I write constants in wordpress?
I have to define a constants to use all over the entire project(i.e: single.php, category.php, my-template.php). Suppose I define a array constant to declare a list of browser name. i.e: array('firefox'=>'Mozilla Firefox','google_chrome'=>'Google Chrome'). Now this constant will be accessible within any php file in my project. I can do this in several ways. But what is the best practice? | Depends on what your project is. If you're developing a theme you would define them at the top of your theme's functions.php file, and if you were developing a plugin you would put them at the top of your main plugin file. | stackexchange-wordpress | {
"answer_score": 3,
"question_score": 0,
"tags": "wp config"
} |
Where in the page load code is wp-cron triggered?
I just spent way too much time trying to troubleshoot why my wp-cron job wasn't running. It seems, under 4.9.8, the only way to run cron is by calling the `wp-cron.php` file as a URL.
The docs say though, that it should run on page loads, though I can't locate where. Any help, please? | The WordPress cron is run by the `wp_cron()` function, which is hooked to run on the `init` hook, which runs on every page load.
`wp_cron()` is defined in `wp-includes/cron.php` and hooked in `wp-includes/default-filters.php`.
The `wp_cron()` function kicks off a `wp_remote_post()` request to `/wp-cron.php`. Some server configurations prevent scripts sending a request to the same domain like this however, so as an alternative you can set the `ALTERNATE_WP_CRON` constant to `true`. When enabled this redirects the user to the current URL but with `?doing_wp_cron=` added to the URL, instead of the post request. | stackexchange-wordpress | {
"answer_score": 1,
"question_score": 0,
"tags": "wp cron"
} |
Members only site - still need the lost password page accessible
My site requires login before viewing any page and it works great:
function wpse_131562_redirect() {
if ( !is_user_logged_in() )
{auth_redirect();
}}
add_action('template_redirect', 'wpse_131562_redirect');
But obviously this means the link to the lost-password page just redirects back to the login page. I've tried changing it to:
function wpse_131562_redirect() {
if ( !is_user_logged_in() || (!ispage('lost-password') ))
{auth_redirect();
}}
add_action('template_redirect', 'wpse_131562_redirect');
But it has the same problem, and when I tried to use wp_lostpassword_url it broke completely.
How can I restrict access to everything other than the lost-password page?
Thanks | I believe your if statement is incorrect it should be an AND (`&&`) not OR
so try
if ( ! is_user_logged_in() && ! is_page( 'lost-password' ) ) {
**EDIT**
Try using `$object = get_queried_object()` for checking the post slug
$object = get_queried_object();
if ( ! is_user_logged_in() && ( ! $object || 'my-account' !== $object->post_name ) ) {
// ...
**EDIT 2** The page slug was wrong so updated in the second example | stackexchange-wordpress | {
"answer_score": 2,
"question_score": 1,
"tags": "functions, login"
} |
Delete all drafts?
This is a common query to delete all post revisions:
DELETE a,b,c
FROM wp_posts a
LEFT JOIN wp_term_relationships b ON (a.ID = b.object_id)
LEFT JOIN wp_postmeta c ON (a.ID = c.post_id)
WHERE a.post_type = 'revision'
Will this work to delete all drafts?
DELETE a,b,c
FROM wp_posts a
LEFT JOIN wp_term_relationships b ON (a.ID = b.object_id)
LEFT JOIN wp_postmeta c ON (a.ID = c.post_id)
WHERE a.post_type = 'draft'
and is it better than this since it also deletes postmeta?
DELETE FROM posts WHERE post_status = ‘draft’ | `draft` is not a `post_type`, it's a `post_status`. So you should use your second block of code with that substitution:
DELETE a,b,c
FROM wp_posts a
LEFT JOIN wp_term_relationships b ON (a.ID = b.object_id)
LEFT JOIN wp_postmeta c ON (a.ID = c.post_id)
WHERE a.post_status = 'draft' | stackexchange-wordpress | {
"answer_score": 2,
"question_score": 0,
"tags": "posts, database, query"
} |
Wordpress super admin login issue. (Automatically logout)
I have created super admin and after login the super admin in admin panel it's not allowed to access other pages like(plugins & users).
It's automatically logout again redirect to admin login page.
Please anyone let me know . Whats is the reason this type of issue accrue.
I have deactivate all plugins & themes and checked the issue still raised. | this issue is might be the primary key in the database.
you have to set primary and index key in the wp_user and wp_usermeta table
do that and let me know if the issue is resolved or is still there
hope this will be help you and waiting for you response | stackexchange-wordpress | {
"answer_score": 1,
"question_score": 0,
"tags": "plugins, multisite"
} |
Link below the footer removal
, it is important to note: The options appear, **if one of the options is set**. They are stored via the keys `upload_path` and `upload_url_path`.
Before:

$ wp option set upload_path foo
$ wp option set upload_url_path bar
After:
 ) : the_post(); ?>
<div class="col-md-4 col-product-item">
<a href="<?php the_permalink() ?>" rel="bookmark" title="<?php the_title_attribute(); ?>"><div class="cat__featured-img"><?php the_post_thumbnail(); ?></div></a>
<h2><a href="<?php the_permalink() ?>" rel="bookmark" title="<?php the_title_attribute(); ?>"><?php the_title(); ?></a></h2>
</div>
<?php endwhile;
else: ?>
<p>Sorry, no posts matched your criteria.</p>
</div>
I broke my head trying to understand how can I exclude the needed categories from this loop and the required posts as well. Would appreciate any help! | Here is a correct way:
<div id="category__product-grid" class="row">
<?php query_posts( array( 'cat' => array(6,-45), 'post__not_in' => array(-598), 'orderby' => 'title', 'order' => 'ASC' ) ); ?>
<?php
// The Loop
while ( have_posts() ) : the_post(); ?>
<div class="col-md-4 col-product-item">
<a href="<?php the_permalink() ?>" rel="bookmark" title="<?php the_title_attribute(); ?>"><div class="cat__featured-img"><?php the_post_thumbnail(); ?></div></a>
<h2><a href="<?php the_permalink() ?>" rel="bookmark" title="<?php the_title_attribute(); ?>"><?php the_title(); ?></a></h2>
</div>
<?php endwhile;
else: ?>
<p>Sorry, no posts matched your criteria.</p>
</div> | stackexchange-wordpress | {
"answer_score": 0,
"question_score": 0,
"tags": "php, categories, loop, exclude"
} |
locking content with overlay/pop up ads
how can i add a pop up before content or before downloading files ?i want to show a custom ad pop up (with option to close ad-similar to what you see in ad.fly url shortener) before a file download /and/or page access . Tried looking in plugins but all of them seem to be old and not updated lately.. | Have you tried Popup Builder plugin? It was being updated 3 days ago. It should work for you. | stackexchange-wordpress | {
"answer_score": 0,
"question_score": 0,
"tags": "functions"
} |
add_action not calling back to function
I am working on a plugin, but add_action doesn't call the callback. The code is as follows:
require plugin_dir_path( __FILE__ ) . 'includes/class-network.php';
$distro = new Classnetwork();
includes/class-network.php:
class Classnetwork {
public function __construct() {
add_action( 'publish_post', array ($this, 'cdn_capture_data') );
}
public function cdn_capture_data( $post_id, $post ) {
print_r ($post);
}
}
Nothing is printed, not error, it just doesn't do anything every time I post a new post. Any ideas where is the error? The __construction is called but not the callback from add_action. | I understand that you are adding the post from wp-admin / Posts / Add New panel? If so then note that the publish_post action is run and the WP is doing redirect so you cannot see any printed data.
Also, your add_action call is missing 4th argument which is number of arguments passed to cdn_capture_data(), by default there is only 1 argument passed so in your case the $post is always null.
The correct code (to actually print the result) should be
class Classnetwork {
public function __construct() {
add_action( 'publish_post', array ($this, 'cdn_capture_data'), 10, 2 );
}
public function cdn_capture_data( $post_id, $post ) {
print_r ($post);
exit;
}
} | stackexchange-wordpress | {
"answer_score": 1,
"question_score": 1,
"tags": "plugin development, actions"
} |
add class to all images inside the content
I have a function like this :
function add_responsive_class($content)
{
$content = mb_convert_encoding($content, 'HTML-ENTITIES', "UTF-8");
if (!empty($content)) {
$document = new DOMDocument();
libxml_use_internal_errors(true);
$document->loadHTML(utf8_decode($content));
$imgs = $document->getElementsByTagName('img');
foreach ($imgs as $img) {
$img->setAttribute('class', 'img-fluid');
}
$html = $document->saveHTML();
return $html;
}
}
add_filter('the_content', 'add_responsive_class');
this adds `img-fluid` to all the images but also it removes the `align-left` , how can i modify the above function to add `img-fluid` to image instead of it removing the other classes?
like --> `<img class ="img-fluid align-left"` | $img->setAttribute('class', 'img-fluid');
This sets the `class` field to a new value. Simply change this line to
$classes = $img->getAttribute('class');
$img->setAttribute('class', $classes . ' img-fluid'); | stackexchange-wordpress | {
"answer_score": 0,
"question_score": 0,
"tags": "theme development, responsive, body class"
} |
Rename wordress plugin
i installed a 3rd party saloon booking plugin on my wordpress site. But i need to rename this plugin name as mysaloon plugin. And im expecting that name will appear even on source code. Is it possible to change a plugin name like that? | Yes, you can change the name of the plugin but keep in mind future updates will not work.
Here is the plugin directory structure
yoursite\wp-content\plugins\ [editing-plugin-folder]
open the folder you will find a .php file in there, edit the file using any editor. you can change the name of the plugin in commented area
/*
Plugin Name: Name according to you
Plugin URI:
*/
save the file refresh your wp-admin dashboard and there you go . | stackexchange-wordpress | {
"answer_score": 0,
"question_score": 0,
"tags": "plugins"
} |
Why after a file is programmatically deleted, is there still a reference in the media library?
I work on a plugin that gets a file uploaded to the upload folder through media. The file is processed if it does not meet x condition the process is aborted and the file is deleted.
The deletion is effective when invoking unlink in this way
if ($counter === 0) {
printMessage('No need to process');
if (unlink($file)) {
printMessage('File removed');
}
return;
}
Here `$file` is a reference to `wp_handle_upload` `$upload['file']`
My case is that after verifying that the file has indeed been deleted from the file system, there is a reference to it in the media library.
 is stored in database.
So if you delete file using `unlink`, you don't delete any rows from DB - so the attachment will be still visible in Media Library.
If you want to delete attachment from ML, you should use WP functions. `wp_delete_attachment` might come in handy.
You can use it like so:
<?php wp_delete_attachment( <ID_OF_YOUR_ATTACHMENT> ); ?> | stackexchange-wordpress | {
"answer_score": 3,
"question_score": 0,
"tags": "plugin development"
} |
How to remove p / br elements from gutenbergs editor
We updated to Wordpress 5.0 on our website, problem is that this includes the new gutenberg editor.
Before this I already removed the WP function that sometimes places `<p>` and `<br>` elementsin your message after you safe with 'wpautop'. However the new editor gives a new problem, the new gutenberg editor places the `<p>` elements in your message when you tab and when you press safe.
Here is an example:. Is there some way to uninstall languages/translations that are not needed? | so you will need at least translations into german.
there shouldn't be other packages loaded for your site. you can find these files in the `language` folders in `wp-content`. there are other `language` folders as well in the plugins or in thmemes. | stackexchange-wordpress | {
"answer_score": 1,
"question_score": 0,
"tags": "translation"
} |
Validate custom fields before save using WordPress Rest API
I want to add custom validation to post(custom post type) before it save into the WordPress. I am using the Rest API to insert the post to custom post type. What I need is the fields which I created using ACF(Advance Custom Fields) should be validated before it actually save into the WordPress Backend. I tried to find the hook action for before save but no luck so far. Quick help will be appreciate. | By searching a lot to API documentation, I found the solution to my problem finally:
function my_rest_prepare_post( $prepared_post, $request ) {
...
}
add_filter( 'rest_pre_insert_posttype', 'my_rest_prepare_post', 10, 3 ); | stackexchange-wordpress | {
"answer_score": 1,
"question_score": 1,
"tags": "custom post types, hooks, advanced custom fields, validation"
} |
Echo term slug op post on archive page
I want to echo the term slug for each post on an archive page.
To get the term slug i'm using the following code:
$terms = get_the_terms( get_the_ID(), 'type_kennisbank' );
That returns me the data that I want:
array(1) { [0]=> object(WP_Term)#18648 (11) { ["term_id"]=> int(28) ["name"]=>
string(10) "Whitepaper" ["slug"]=> string(10) "whitepaper" ["term_group"]=>
int(0) ["term_taxonomy_id"]=> int(28) ["taxonomy"]=> string(15)
"type_kennisbank" ["description"]=> string(0) "" ["parent"]=> int(0)
["count"]=> int(3) ["filter"]=> string(3) "raw" ["term_order"]=> string(1) "0" } }
If I want to echo the slug I'm using:
echo $terms["slug"]
However it returns nothing. I already found a solution to echo the term slug but I'm wondering why my own echo code doesn't return the slug.
Anyone who can explain this? | The `get_the_terms` function returns array of `WP_Term` objects. So you need to use something like this to echo a single term slug:
echo $terms[0]->slug;
Also be aware of results of this function. As documentation says it returns:
> Array of WP_Term objects on success, false if there are no terms or the post does not exist, WP_Error on failure.
So you need some checks before trying to echo terms. The following code may help you.
$terms = get_the_terms( get_the_ID(), 'type_kennisbank' );
if ( $terms && ! is_wp_error( $terms ) ) {
foreach ( $terms as $term ) {
echo $term->slug;
}
} | stackexchange-wordpress | {
"answer_score": 2,
"question_score": 0,
"tags": "terms"
} |
Missing background image setting in admin of twenty nineteen
I have installed fresh Wordpress 5.0 with twenty nineteen theme. In admin panel for home page below colors setting a link to setting background image should be visible. See < (41th second).
);
Is there something I am missing here. I have not used $wpdb much, so am sure I must be missing something.
I appreciate any help here.
Thanks! | Without an error message, it is difficult to tell the exact problem. It is important to debug within WordPress and check your webserver error logs.
One problem is your call of `prepare()`. The method takes 2 or more arguments, you only passed 1. Instead try the following
$update_status = $wpdb->query($wpdb->prepare(
"UPDATE {$wpdb->prefix}wcpv_commissions SET commission_status = %s WHERE vendor_id = %d AND order_date BETWEEN %s AND %s",
$status,
$vendor_id,
$date1,
$date2
)); | stackexchange-wordpress | {
"answer_score": 4,
"question_score": 0,
"tags": "query, wpdb, sql"
} |
Changing user_nicename
**user_nicename** has the same value with **user_login**. I want to change **user_nicename** value only by using code snippet into functions.php or wp-config.php. Is it possible without using phpmyadmin or any plugin? | Yes, you can use `wp_update_user()`:
wp_update_user( array(
'ID' => 123,
'user_nicename' => 'value'
) );
Just replace `123` with the proper user ID, and `value` with the preferred `user_nicename` value.
The function also enables you to change the value of other fields in the WordPress users table (`wp_users`). | stackexchange-wordpress | {
"answer_score": 5,
"question_score": 3,
"tags": "php, database, users, login, mysql"
} |
advanced custom fields if field has value show main div
<?php if( get_field('packaging_details','port','lead_time') ): ?>
<div class="prd-overview-list">
<h3>Packaging & Delivery</h3>
<ul>
<?php if( get_field('packaging_details') ): ?><li><p>Packaging Details</p> <p><span><?php the_field( 'packaging_details' ); ?></span></p></li><?php endif; ?>
<?php if( get_field('port') ): ?><li><p>Port</p> <p><span><?php the_field( 'port' ); ?></span></p></li><?php endif; ?>
<?php if( get_field('lead_time') ): ?><li><p>Lead Time</p> <p><span><?php the_field( 'lead_time' ); ?></span></p></li><?php endif; ?>
</ul>
</div><?php endif; ?>
i want if all 3 fields are empty, hide full div. and when any field have value, show full div | Please try below and let me know if any query.
<?php if( get_field('packaging_details') || get_field('port') || get_field('lead_time')): ?>
<div class="prd-overview-list">
<h3>Packaging & Delivery</h3>
<ul>
<?php if( get_field('packaging_details') ): ?><li><p>Packaging Details</p> <p><span><?php the_field( 'packaging_details' ); ?></span></p></li><?php endif; ?>
<?php if( get_field('port') ): ?><li><p>Port</p> <p><span><?php the_field( 'port' ); ?></span></p></li><?php endif; ?>
<?php if( get_field('lead_time') ): ?><li><p>Lead Time</p> <p><span><?php the_field( 'lead_time' ); ?></span></p></li><?php endif; ?>
</ul>
</div><?php endif; ?>
Hope it will help you ! | stackexchange-wordpress | {
"answer_score": 0,
"question_score": 0,
"tags": "advanced custom fields"
} |
How to copy user_nicename value into user_login
a hacker put value "admin" into all user_login fields. i need to copy `user_nicename` value into the `user_login` so users can login. is there a SQL command i can run to do this task in bulk, as their 1000s of users and doing manually would a hassle. kindly help if you can. thanks ! | Run the following SQL query in PHPMyAdmin or similar.
UPDATE wp_users SET user_login = user_nicename;
`wp_users` is the table for users (make sure it matches yours) | stackexchange-wordpress | {
"answer_score": 2,
"question_score": 0,
"tags": "users, sql"
} |
How to change the color of a menu item
I want to change color to red for one menu page "Logowanie".  would need to be done on the live site. On that day, Gutenberg loaded as expected, and I also installed the Classic Editor plugin, intending to activate/deactivate through my tests. This worked as intended that day, but my time was cut short. Yesterday and today, I've tried to pick up from where I left off, however now all posts/pages are loading in the classic format even with the Classic Editor deactivated. I deleted the plugin in hopes of forcing Gutenberg, but that made no difference. I don't do any caching on the dev site. With last night's release of 5.0.1, I was hoping it would force Gutenberg to come up, but it still has not. I used WP-CLI to verify the checksums in case something old somehow has stuck, but they all matched. I feel like I'm at a dead-end, what should I check next? | The problem was caused by the plugin Page Builder by SiteOrigin v2.9.6. | stackexchange-wordpress | {
"answer_score": 1,
"question_score": 0,
"tags": "block editor"
} |
How can I create a plugin that changes the title color of a website?
I'm new to building plugins and just for testing purposes I would like to build a simple plugin that changes the title of website. What hooks or filter would I need? | The exact way to do this may vary based on the theme you are using, but here's a simple plugin that hooks into the `wp_head` action hook and adds some style to the header:
<?php
/**
* @package PACKAGE_NAME
*/
/*
Plugin Name: Plugin name
Plugin URI:
Description: Plugin Description
Version: 1.0.0
Author: Plugin Author
Author URI:
License: Plugin License
Text Domain: text-domain
*/
add_action( 'wp_head', 'wpse321903_add_styles' );
function wpse321903_add_styles(){ ?>
<style>
.page-title {
color: white;
}
</style><?php
} | stackexchange-wordpress | {
"answer_score": 1,
"question_score": 1,
"tags": "plugin development"
} |
Unable to disable Gutenberg with plugin Classic Editor or Disable Gutenberg
I updated my Wordpress to version 5.0
After updating, I install "Classic Editor" plugin to replace Gutenberg.
The post editor changed to Classic Editors.
Today I received a mail my site is updating to Wordpress 5.0
My post editor became Gutenberg.
I checked the setting is Classic Editors, but it still Gutenberg.
I tried "disable Gutenberg" plugin and activated it.
No changes to my post editor, it still Gutenberg.
How to change it back to Classic Editor?
 that also disable or replace Gutenberg. Why? Because it may cause loading of redundant scripts, which may in turn lead to unexpected/untested results."_
You stated you are running the Classic Editor plugin with "Disable Gutenberg". This is the conflict. Otherwise, clear your cache in the CMS & browser to see if it makes any difference.
**Solution:**
1. Without installing the "Disable Gutenberg" plugin, navigate to the classic editor settings at: /wp-admin/options-writing.php#classic-editor-options
2. Under the settings for "Default editor for all users" use the buttons to toggle between 'Classic Editor' & 'Block Editor' (Gutenberg). Save the settings & reload the page. | stackexchange-wordpress | {
"answer_score": 1,
"question_score": 1,
"tags": "block editor"
} |
Print terms with taxonomy and metabox value
I create metabox `serial_language` with ACP plugin into custom taxonomy name is `serial`.
And I want to get only terms, in which custom field value is `english, arabic`.
How to get only terms which have custom fields value `english or arabic`?
$wcatTerms = array(
'get_terms' => 'serial',
'hide_empty' => 0,
'parent' =>0,
'tax_query' => array(
'relation' => 'AND',
array(
'get_terms' => 'serial',
'field' => 'serial_language',
'value' => array( 'english', 'arabic' ),
)
));
foreach($wcatTerms as $wcatTerm) :
echo '<a href="' .get_term_link( $wcatTerm->slug, $wcatTerm->taxonomy ). '">' .$wcatTerm->name. '</a>';
endforeach; | Try This:
$args = array(
'hide_empty' => false,
'relation' => 'OR',
array(
'key' => 'serial_language',
'value' =>'english',
'compare' => 'LIKE'
),
array(
'key' => 'serial_language',
'value' =>'arabic',
'compare' => 'LIKE'
),
'taxonomy' => 'serial',
);
$terms = get_terms( $args );
hope this will help | stackexchange-wordpress | {
"answer_score": 1,
"question_score": 1,
"tags": "custom taxonomy, custom field, query, terms"
} |
Add input radio menu to post
Is there any function to add radio buttons to post and how can I call it? (exampe on img). Thank you for suggestion  && isset( $_GET['page'] ) && 'PLUGIN-NAME' == $_GET['page'] ) {
// replace the footer with empty string
add_filter( 'admin_footer_text', '__return_empty_string' );
} | stackexchange-wordpress | {
"answer_score": 1,
"question_score": 0,
"tags": "plugins, admin, footer, text"
} |
Wordpress Gutenberg home page "edit Page" option missing
I try to understand customising of default theme, in my case twenty nineteen. After I create a new page on the top horizontal bar there is an option "Edit Page" visible. Why that option is missing on the bar for home page?
What is the best way to customise the home page?
Home page:  of your theme, cannot be edited by neither, `Guttenberg` nor `Classic Editor`.
Create a child theme, and copy `index.php` from your parent theme to the child theme. Then you can edit your child's `index.php`, using external text editor. | stackexchange-wordpress | {
"answer_score": 0,
"question_score": 0,
"tags": "editor, block editor"
} |
Redirect From Url To Url
I want to redirect the same directory, but different url structure. The url structure I use: http:example.com/car/cadillac/image/2
I want to direct http: example.com/car/cadillac/image/ url. Because this url is 404. I want to redirect to http: example.com/car/cadillac/
(In fact, the problem comes from the "image" link structure: How to change the permalink structure of a master page?) As an alternative, I thought about the routing rule. But the cpanel 301 redirect is not successful.
**http: example.com/car/cadillac/image/** How can we redirect the URL to **http: example.com/car/cadillac/** ? | The easiest way to do is by using Redirection plugin. Follow these steps:
1. Install and activate the plugin.
2. Head to **Tools > Redirection**.
3. Enter your **Source URL** (example.com/car/cadillac/image/) and **Target URL** (http: example.com/car/cadillac/).
4. Finally, click on "Add Redirection" button. | stackexchange-wordpress | {
"answer_score": 1,
"question_score": 0,
"tags": "permalinks, pages, redirect"
} |
Can't add to time?
What's the best way to add to `time()`?
For example: `time() + 5` will return `5`, not the current unix timestamp with 5 added to it. Any ideas? Thanks | Oh you have to wrap in quotes.
(time() + 5)
Works. **_Sigh_** | stackexchange-wordpress | {
"answer_score": 0,
"question_score": 0,
"tags": "php, date, date time, timestamp"
} |
How do I remove header/page-title image in farvis theme?
I'm working with farvis theme. In that theme I removed background image in customize >> page titles & Breadcrumbs >> background image >> remove. But after I clicked save and reloaded the site another image is showing on screen in header image, I didn't find that image in Media Library.
Why this happening after removing header image in theme option. Tell me any additional CSS code to solve this problem.
Here is my screen shots. My desktop view {
$siteURL = site_url();
$logoutURL = wp_logout_url(home_url());
echo '
<div class="signin_container">
<h4 class="signin_footer_head">Log In To My Account</h4>
<a href="'.$siteURL.'/login/">Log In</a>
<a href="'.$siteURL.'/register/">Sign Up</a>
</div>
';
}
add_shortcode('footerShortcode', 'footer_shortcode'); | You can use a conditional tag to check if the user is logged in. Conditionals are very common in W, I would suggest you give this page a read.
Here is an example.
function footer_shortcode(){
if (is_user_logged_in()){
echo '
// Logged In Content
';
}else{
echo '
// Logged Out Content
';
}
}
add_shortcode('footerShortcode', 'footer_shortcode'); | stackexchange-wordpress | {
"answer_score": 1,
"question_score": 1,
"tags": "conditional tags, conditional content"
} |
WordPress CSS problems with controls
Where and how should I even begin to fix terrible design problems? I can't change the theme, I must learn how to fix it the current one, I guess via CSS? How to align all textboxes properly, how to change box (top is gray) color and button color as well? These are all in simple pages via shortcodes. Thanks.

I have an email triggered like below. I want a user to be able to customize the content.
I want to provide the user to be able to put `esc_html($user->display_name)` somehow may some thing with a text like `{{user_name}}`
$body = sprintf('Hey %s, your awesome post has been published!
See <%s>',
esc_html($user->display_name),
get_permalink($post)
);
// Now send to the post author.
wp_mail($user->user_email, 'Your post has been published!', $body);
Is it possible to do? | I would just use `str_replace()` to handle a "pseudo" shortcode. Something like this:
$body = sprintf('Hey {{username}}, your awesome post has been published!
See <%s>', get_permalink($post) );
// Add replacement values to the array as necessary.
$old = array( '{{username}}' );
$new = array( esc_html($user->display_name) );
$body = str_replace( $old, $new, $body );
// Now send to the post author.
wp_mail($user->user_email, 'Your post has been published!', $body);
I just worked from what you started with. I'm assuming you're doing something ahead of this to get the `$user` object. Also, I made the replacement values for `str_replace()` as arrays, so you can add to that as necessary (instead of running it multiple times). | stackexchange-wordpress | {
"answer_score": 0,
"question_score": 0,
"tags": "plugin development, wp mail"
} |
WooCommerce how to checkout a product without adding it to the cart
I am trying to implement this in my website:
Having a second button on a single product next to the"Add to cart" button, let that button be "Buy now".
When the add to cart button is clicked, the product will be added to the cart, when the Buy now button is clicked the client will be redirected to the checkout page where he will only checkout that single product, and that product will not be added to the cart.
For example, if the client was having products A and B in the cart, and clicks the Buy now o product C, he will only checkout for that product, and C will never be added to the cart.
I was thinking of a way to implement this, and I thought that having two different checkout pages might help,.. I don't know if it can, if you have a solution on how I can do this, I'd love to hear from you.
Thanks | You could code your own, and connect to a payment gateway's API, but plenty have tread this road before you so stand on their shoulders. Two possibilities:
Stripe One Click Checkout plugin by WooCommerce
PayPal One Click Checkout plugin by StoreApps | stackexchange-wordpress | {
"answer_score": 2,
"question_score": 0,
"tags": "woocommerce offtopic"
} |
Is there a cleaner way to get post count for a category in category.php?
Building the category.php I'm curious to know if there is a better way to get the count of posts without `wp_query`? In the past I've called:
* `single_cat_title()` to render the category
* `category_description()` to render the category description
and to build a separator after each post but not the last on the page or last in `get_option('posts_per_page')` I've used:
$category = get_queried_object();
$category_total = $category->count;
From research I did see How to get Total Post In a Selected category which was authored in 2011. `wp_count_posts()` counts all posts in a blog which I dont think would be good on performance.
$category = get_category($id);
$count = $category->category_count;
From Count how many posts in category I think requires `wp_query`? Is there a better way to get the count of posts in a category for category.php? | What you've got is basically correct. This is the correct method for getting the total number of posts in the currnet category:
$category = get_queried_object();
$category_total = $category->count;
There shouldn't be any performance impact from using this, as the `count` property is only updated when new posts are published, and doesn't need to be calculated each time it's used.
To get the number of posts on the current page though, `get_option( 'posts_per_page' )` is not the best option, because it will be the incorrect number on the last page, which could have less than the total number of posts per page.
To get that number you need to check the global `$wp_query` object:
global $wp_query;
$post_count = $wp_query->post_count; | stackexchange-wordpress | {
"answer_score": 1,
"question_score": 1,
"tags": "categories"
} |
Creating select dropdown with parent-level custom post types
I'm trying to create a dropdown with an option for each top-level parent. I've gotten the query down because when I print the results, I see the posts I'm looking for. My code is also creating the right number of options, but it's not entering the info as I'd expect. Here is the code I have:
<select class="filters-select">
<option value="*">Show All</option>
<?php
$args = array(
'post_type' => 'locations',
'post_status' => 'publish',
'order_by' => 'title',
'order' => 'asc',
'post_parent' => 0,
'posts_per_page' => -1
);
$posts = get_posts( $args );
foreach ( $posts as $post ) {
echo "<option value='." . $post->slug . "' class='" . $post->slug . "'>" . $post->name . "</option>\n";
} ?>
</select> | Found the answer. I was using the terms nomenclature to call my info. Had to update to:
echo "<option value='." . $post->post_name . "'>" . $post->post_title . "</option>\n";
And now it's working just fine. (I also eliminated class cause I didn't need it here.) | stackexchange-wordpress | {
"answer_score": 1,
"question_score": 1,
"tags": "custom post types, loop, select"
} |
wordpress wp-admin css not loading
> previously its have SSL now don't have SSl
my word press admin dashboard css not loading but home page and other page are working perfect any one know how to fix this?
> no ssl its just http
;
add this line your wp-config,php
i try everything still not loading | I had the same issue a few months back I tried this and this works for me.
define('FORCE_SSL_LOGIN', false);
define('FORCE_SSL_ADMIN', false);
define( 'CONCATENATE_SCRIPTS', false );
define( 'SCRIPT_DEBUG', true );
try to load wp-admin with SSL.
After reloading it looks OK, maybe after re-login, set SCRIPT_DEBUG to false.
hope this help | stackexchange-wordpress | {
"answer_score": 9,
"question_score": 9,
"tags": "wp admin, admin css"
} |
How to insert the number of posts from the category in wp _title?
For example, the site has a category "News", in which there are 37 posts num.
How to insert into **wp_title** the number of records (37) in this category.
those, if we go to the "News" category, the title should be displayed:
<title>37 posts in News category | Site name</title>
Help me please, Regards, Anna | If your theme supports WordPress adding the title tag using `add_theme_support( 'title-tag' );` (it should!) you can use the `document_title_parts` filter to insert the post count in the right place without needing to parse the full title or modify existing elements that might have been customised, such as the separator:
function wpse_323260_document_title_category_count( $title ) {
if ( is_category() ) {
$category = get_queried_object();
$title['title'] = sprintf(
'%d posts in %s Category',
$category->count,
esc_html( single_cat_title( '', false ) )
);
}
return $title;
}
add_filter( 'document_title_parts', 'wpse_323260_document_title_category_count' ); | stackexchange-wordpress | {
"answer_score": 4,
"question_score": 3,
"tags": "wp title"
} |
Permalink structure has suddenly changed
I've just noticed that the permalink structure on my site has changed, I've tried the usual stuff (flushing permalinks etc) but to no avail.
The original structure was
`mysite.co.uk/blog/some-title`
but it's now become
`mysite.co.uk/some-title`
In a nutshell the 'blog' part of the url has completely disappeared.
I haven't made any changes to the permalink settings, or any of the theme files - does any one have any ideas? | Fixed!
Somehow the word blog had removed itself from /blog/%postname%/ in custom post structure, possibly on a recent permalinks flush.. | stackexchange-wordpress | {
"answer_score": 0,
"question_score": 0,
"tags": "permalinks"
} |
Open Featured Image Modal in WordPress Gutenberg onClick of a button
I am using the metabox.io plugin. I am looking for a way to open the new WordPress Gutenberg editors featured image modal onClick of a button inside my custom metabox.
Is there a function that I can use in order to make the featured image modal popup onClick of a button?
Basically, I want to replicate the functionality of the onClick of “Set featured image”.
 {
$u_time = get_the_time('U');
$u_modified_time = get_the_modified_time('U');
if ($u_modified_time >= $u_time + 86400) {
$updated_date = get_the_modified_time('F jS, Y');
$updated_time = get_the_modified_time('h:i a');
$custom_content .= '<p class="last-updated" style="text-align:right">Last updated on '. $updated_date . ' at '. $updated_time .'</p>';
}
$custom_content .= $content;
return $custom_content;
}
add_filter( 'the_content', 'wpb_last_updated_date' );
It works,but I don`t want to show **it** on my home page.
How can I do ? | You can check for your "home page" at the start of your function by using `is_home()` and/or `is_front_page()` and just return original content without date. See is_home vs is_front_page
function wpb_last_updated_date( $content ) {
if ( is_home() || is_front_page() ) return $content; //homepage return content without date
// your original function code
}
Alterantively you could embes your add_filter in an if statement | stackexchange-wordpress | {
"answer_score": 1,
"question_score": 1,
"tags": "functions, filters"
} |
Unable to create directory uploads/2018/12. Is its parent directory writable by the server?
Few days ago I migrated my site to a new server and the problem started after that, before migrating everything was fine. Now, when I click on add media and select any image it says... Unable to create directory uploads/2018/12. Is its parent directory writable by the server? I found some answers to this question, and have tried to edit the options.php file but no luck yet also I have checked it and fourd that the permissions on above directory is 777. So please check the same and help me. | This is the common issue we are facing when we change the server of the website.However in this there is no issue of permission to folder . In your admin, go to Settings/Media and change the upload path to that of the new server.

and the missing file address is :
I am wondering why I got this error? in the older versions of WordPress there was not such a file or directory but I was not getting this error. I was hoping this will be fixed in the latest WP update v5.0.1 but it's not.
Is it a problem in my theme or WP or maybe something else? | First I tried to disable all plugins and change theme to the default WordPress theme and error is showing yet.
Then tried to install a new WordPress 5.0.1 and got 2 errors:
theme.min-rtl.css:1 Failed to load resource: the server responded with a status of 404 (Not Found)
style.min-rtl.css:1 Failed to load resource: the server responded with a status of 404 (Not Found)
I changed the WP language to English and the errors gone. and the errors comeback on all right to left languages. so it seems to be a WP issue and needs to be fixed in future versions. | stackexchange-wordpress | {
"answer_score": 1,
"question_score": 0,
"tags": "errors, 404 error"
} |
Woocomerce add info after order email prouct item
I'm trying to add some labels after woocommrce order email items.
Example: We can do that on cart by using this filter.
add_filter( 'woocommerce_cart_item_name', array( $this, 'wc_esd_show_date_cart_page' ), 10, 2 );
This calls the wc_esd_show_date_cart_page() function and show its data after the item name.
I want to do the same for order email items, anyone know there have some filter for it, or another way to do this.

use it similarly to the cart filter above.
For a visual representation if you want the additional information somewhere else see this link:
<
You can also always go right to the source and see all the hooks/filters/actions in woocommerce: <
as an example:
add_action( 'woocommerce_order_item_meta_end', 'rt_order_item_meta_end', 10, 4 );
function rt_order_item_meta_end( $item_id, $item, $order, $plain_text ){
echo '<p>cool item detail</p>';
} | stackexchange-wordpress | {
"answer_score": 1,
"question_score": 0,
"tags": "plugins, woocommerce offtopic"
} |
Get a value inside a get_post_meta Array
I am editing a Wordpress theme and want to output a value that's inside an array in the post meta array.
My code is:
$banner_subtitle = get_post_meta( $post_id, 'header_section_meta', true );
echo print_r($banner_subtitle);
And my output is:
Array
(
[section_mode] => banner
[header_section_id] =>
[slider_alias] =>
[banner_subtitle] => SUBTITLE 1
[banner_image] =>
[is_banner_image_parallax] => 0
[banner_image_repeat] => repeat-x
[banner_mask] =>
)
1
How can I modify my code so that the output is the value of the **banner_subtitle** , in this case "SUBTITLE 1", instead of that whole array? Thank you. | $banner_subtitle = get_post_meta( $post_id, 'header_section_meta', true );
if (!empty($banner_subtitle['banner_subtitle'])) {
echo $banner_subtitle['banner_subtitle'];
}
or as a ternary
$banner_subtitle = get_post_meta( $post_id, 'header_section_meta', true );
echo !empty($banner_subtitle['banner_subtitle']) ? $banner_subtitle['banner_subtitle'] : ''; | stackexchange-wordpress | {
"answer_score": 1,
"question_score": 0,
"tags": "php"
} |
Subsets and Splits
No saved queries yet
Save your SQL queries to embed, download, and access them later. Queries will appear here once saved.