INSTRUCTION
stringlengths
11
999
RESPONSE
stringlengths
0
999
SOURCE
stringlengths
16
38
METADATA
dict
prevent/block direct access to a thank you page how to prevent/block direct access to a thank you page, only access if redirected from submiiting a form (in a different page)?
If the form is redirecting from one page only, you can easily use `wp_get_referer()` to check for it and if not, redirect. add_action('template_redirect', function() { // ID of the thank you page if (!is_page(12345)) { return; } // coming from the form, so all is fine if (wp_get_referer() === 'URL_OF_FORM') { return; } // we are on thank you page // visitor is not coming from form // so redirect to home wp_redirect(get_home_url()); exit; } );
stackexchange-wordpress
{ "answer_score": 6, "question_score": 4, "tags": "redirect" }
WP-CLI get all posts from certain post type and taxonomy term I am trying to select all the posts from certain post type and term in custom taxonomy, but what ever I try gets me just the list of all the posts in certain post type wp post list --post_type=custom-type --fields=post_name,ID This returns all posts in cpt `custom-type`, but say I want to list only posts in term that has id 49, I tried wp post list --post_type=custom-type --taxonomy=custom-tax --terms=49 --fields=post_name,ID But again I got everything. In the documentation it says that the arguments are passed to WP_Query, but how do I do a `tax_query`? EDIT: Ok so `wp term list custom-tax` will return the correct list of terms in the taxonomy. So I need to see how to use this to my advantage...
Assume we have a custom post type `movie` (slug) and a custom taxonomy `cast` (slug). **1)** To find all movies starring _Emily Watson_ , stored with the term slug `emily-watson`, we can do: wp post list --post_type=movie --cast=emily-watson to list all her movies. **2)** To find all movies featuring _Elizabeth Taylor_ **or** _Richard Burton_ , stored with the term slugs `elizabeth-taylor` and `richard-burton`, we can do: wp post list --post_type=movie --cast=elizabeth-taylor,richard-burton We should at least get _Cleopatra (1963)_ ;-)
stackexchange-wordpress
{ "answer_score": 7, "question_score": 5, "tags": "wp cli" }
Make medium_large images available to insert into post Our post have a Max width of 768, so using the medium_large images is the preferred size for our authors. I ssumed since medium_large isnpart of core, this would be included but I don't see an easy way to activate that option. Can this be activated as a new hook in our functions.php?
since I'm using a size already generated by WP, I just needed to add: add_filter( 'image_size_names_choose', 'fresh_custom_sizes' ); function fresh_custom_sizes( $sizes ) { return array_merge( $sizes, array( 'medium_large' => __( 'Medium Large' ), ) ); }
stackexchange-wordpress
{ "answer_score": 2, "question_score": 1, "tags": "images" }
Using function from enqueued .js file in theme in plugin? I am developing a theme as well as a few plugins that go along with it. I'm having trouble figuring out dependencies of enqueued files between a theme and a function. If I enqueue a custom .js file in my theme, and then make that file as a dependency of a file I enqueue in my plugin, should I expect the functions from the theme .js file to work in the plugin .js file? In theme functions.php: wp_register_script( 'theme-script', 'path/to/theme/script.js', array('jquery')); wp_enqueue_script( 'theme-script'); In plugin my-plugin-name.php: wp_enqueue_script( 'plugin-script', 'path/to/plugin/script.js', array('theme-script')); Is this the way I should do this in order to use functions from the theme .js file in my plugin?
Yes. Dependencies work across all of WP, it doesn't matter where you enqueue your script. All that matters is that you define your dependencies correctly, and you're doing that. If, however, you plan to publish both the theme and the plugin as standalone versions, you shouldn't rely on your plugin being used with your theme, and add the same script to your plugin (using the same name so it'll only be loaded once by WP). If theme and plugin are only available as a combo, don't worry about it.
stackexchange-wordpress
{ "answer_score": 1, "question_score": 0, "tags": "plugin development, theme development, jquery, wp enqueue script" }
How to: Rest endpoint returning empty object I'd like to implement a custom REST endpoint that can also return an empty object. However, in the case where it should return an empty object, the empty associative array returned by the callback is transformed to an empty array. How can I force the endpoint to transform the array into an object like I can in `json_encode` by setting the `JSON_FORCE_OBJECT` flag? function rest_cb() { return array(); // this will result in the REST response [] but {} is required } function on_rest_api_init() { register_rest_route('ns/v1', 'empty-object', 'rest_cb'); }
Found the solution: By casting the return value to an object, it is ensured that in case of an empty array, an empty object will be returned on REST request. Enhancing on my initial example, this code would work: function rest_cb() { return (object) array(); }
stackexchange-wordpress
{ "answer_score": 3, "question_score": 3, "tags": "plugin development, rest api, json, endpoints" }
How to redirect user to a specific page based on username? There are plugins to redirect a user role to a specific page, but is there one that can redirect a username to a specific page? I need _userA_ to see **only** the page for _userA_. And _userB_ to see **only** the page for _userB_ , etc. All users would have the subscriber role but couldn't access one another's pages.
To redirect to a page, you can try this: add_action( 'template_redirect', 'wpse_290317_redirect_user_to_page' ); function wpse_290317_redirect_user_to_page() { $current_user = wp_get_current_user(); if( 'username' == $current_user->user_login ) { wp_redirect( ' ); exit; } } But I think you want to redirect on login, right? In that case, the following code should help: add_action( 'login_redirect', 'wpse_290317_redirect_user_to_page', 999, 3 ); function wpse_290317_redirect_user_to_page( $redirect_to, $request, $user ) { if( 'username' == $user->user_login ) { $redirect_to = ' } return $redirect_to; }
stackexchange-wordpress
{ "answer_score": 2, "question_score": 1, "tags": "redirect, login" }
"Warning: count()" printing in Page templates I recently made a local copy of an existing site to make development changes. Most everything is working fine in the local version, except that at the top of any Page I see this error (sometimes more than once) – `Warning: count(): Parameter must be an array or an object that implements Countable in /[website directory]/wp-includes/post-template.php on line 284 ` It looks like `<?php wp_head(); ?>` is throwing the error when php checks to see if the selected post has more than one page, and that it's the `$pages` variable that's failing. I've tried manually setting `$pages` to an empty array before that, but that didn't make any difference. The only other thing I can think of is that my dev environment is running php 7.2 but the production server (which is working fine) is running 5.6. Might that have anything to do with this issue?
Turns out the problem was Jetpack. I looked through the `<head>` to see where in the stack it was breaking and it was right in the middle of the Jetpack plugin code. Looks like it's being worked on here: < under "PHP warnings." Since Jetpack isn't necessary for my dev server on this project, I deactivated it and haven't had any errors since.
stackexchange-wordpress
{ "answer_score": 0, "question_score": 0, "tags": "wp head" }
How do I target a links only in a custom post type and only in the p tag? < This is a page under a custom post type for applications (< We want every hyperlinked text to be underlined, but only in the paragraphs, not in the ul's. So on the example page I gave, I'm looking for each of these to underline: < Of course we could do it all manually, but there has to be a way through CSS to do this. We have 30 of these pages now and always are tweaking.
You can try this- .single-application .entry-content p > a { text-decoration: underline; } Where `.single-application` is based on your post type, `.entry-content` is the wrapper of your post content. See the page source- ![enter image description here](
stackexchange-wordpress
{ "answer_score": 2, "question_score": -2, "tags": "custom post types, css" }
Send default WooCommerce email when switching from custom order status I have implemented custom order status `on-review` and now I need to send WooCommerce default on-hold email when switching order statuses from `on-review` to `on-hold`. In order to do this, I have to add new `woocommerce_order_status_on-review_to_on-hold_notification` action that will run `trigger` method of `WC_Email_Customer_On_Hold_Order` class. It looks like there are no hooks nor filters to add this action to default `WC_Email_Customer_On_Hold_Order` constructor and I have to override this class with custom one. To do so, I need to define my custom `WC_Email_Customer_On_Hold_Order` class after `WC_Email` class is defined, and before `WC_Email_Customer_On_Hold_Order` class is defined. The problem is that both these classes are included during `init` method execution of `WC_Emails` and there are no hooks between file inclusions. Is there any other way to solve my problem?
Looks like I was overcomplicating things. This is the solution: add_filter( 'woocommerce_email_classes', 'custom_woocommerce_email_classes', 10, 1 ); function custom_woocommerce_email_classes( $email_classes ) { $email_classes[ 'WC_Email_Customer_On_Review_Request' ] = include_once 'includes/classes/class-wc-email-customer-on-review-request.php'; // Register custom trigger to send on-hold email when status is switched from on-review to on-hold. add_action( 'woocommerce_order_status_on-review_to_on-hold_notification', [ $email_classes[ 'WC_Email_Customer_On_Hold_Order' ], 'trigger' ], 10, 2 ); return $email_classes; }
stackexchange-wordpress
{ "answer_score": 0, "question_score": 0, "tags": "customization, woocommerce offtopic, order, email, post status" }
Do multiple revisions really slow down WordPress? I have read numerous times that I should clean up my database to keep performance high. Keeping multiple revisions of posts is always cited as a big performance stealer. I'm suspicious of this claim. I get that the table will be significantly larger with 10 revisions than 2, but will it really be slower in operation? Given that there are indexes (or should be) on the fields you look things up on frequently, queries should still be nearly as quick. I can't see any difference in my own sites, but I don't have that much data. I'm curious at what point, sizewise any improvement would actually start to show up, if indeed one ever does. I'm not arguing for site owners to up the number of revisions they want to keep, I'm just trying to understand the real world effect, compared to the big performance improvement claims I so often see.
Having 2 revisions or 100,000 will not change front end performance in a default plugin-less WordPress setup However plugin and theme authors who do not query the database correctly, could end up accidentally searching/querying revisions, which could have some performance issues Here’s a snippet on it > revisions take up space in your WordPress database. Some users believe that revisions can also affect some database queries run by plugins. If the plugin doesn’t specifically exclude post revisions, it might slow down your site by searching through them unnecessarily
stackexchange-wordpress
{ "answer_score": 5, "question_score": 5, "tags": "performance, revisions" }
Contact Form 7 Custom Post Action I found this thread here discussing this topic: < However it seems that using the following code does not work as the contact form is submitting with ajax back to CF7 and ignoring the post action. add_filter('wpcf7_form_action_url', 'wpcf7_custom_form_action_url'); function wpcf7_custom_form_action_url(){ return 'www.myposthandler.com'; } Is there a way to disable the ajax submission? Site where this is happening: < the newsletter subscription form in the footer is what I am trying to alter.
As per the CF7 Documentation, you can disable AJAX form submission by placing the following code in your `wp-config.php` define('WPCF7_LOAD_JS', false);
stackexchange-wordpress
{ "answer_score": 8, "question_score": 4, "tags": "ajax, forms, plugin contact form 7" }
Header has extra HTML block at top before my code I've been trying to fix the issue where wp_head loads in the body tag in wordpress, and I've discovered that when I look at the page source, an extra HTML block appears before the code from my header.php file. Here's what I've tried: 1. Setting wp_debug to true 2. ensuring that charset is UTF-8 3. removing all text before the beginning of !DOCTYPE 4. check for missing closing tags This is my `header.php` file ![enter image description here]( Here is the output source: ![You can see that my code is being rendered correctly.. but why am I getting a HTML block at the start of the document??]( You can see that my code is being rendered correctly.. but why am I getting a HTML block at the start of the document?? Any help would be amazing. Thanks so much
I am really not sure what's causing this. Can you try with a minimal content in `header.php`? Something like this and see if the problem occurs? <!doctype html> <html <?php language_attributes(); ?>> <head> <meta charset="<?php bloginfo( 'charset' ); ?>"> <meta name="viewport" content="width=device-width, initial-scale=1"> <?php wp_head(); ?> </head> <body <?php body_class(); ?>> And, meta tags doesn't support `class` attributes like you have in line 11.
stackexchange-wordpress
{ "answer_score": 0, "question_score": 2, "tags": "php, html, wp head" }
Ajax Redirect role = 'Editor' to their Dashboard after register How to redirect the user with role `Editor` to their respective dashboard after register? Here is the **Ajax Script:** `wp_localize_script('jquery_login','ajax_object',array('ajax_url'=>admin_url('admin-ajax.php'),'redirecturl' => get_dashboard_url()));` The **Ajax Code:** success: function(data){ if(data.reg==true){ jQuery('#reg_message').prepend('Register Successfully. Redirecting...'); window.setTimeout(function(){ document.location.href = ajax_object.redirecturl; }, 2000); } I also tried this `window.location.href = ajax_object.redirecturl;` but the url redirect to admin login page.
You should set your address with the static method. For example: wp_localize_script( 'jquery_login', 'ajax_object', array( 'ajax_url' => admin_url('admin-ajax.php'), 'redirecturl' => get_bloginfo('url') . '/user/dashboard' // Your Address ) );
stackexchange-wordpress
{ "answer_score": 2, "question_score": 2, "tags": "ajax, user roles, editor, user registration" }
Setting dirty on customizer When you are using the wordpress customizer, if you don't make any changes to the settings, the wordpress customizer doesn't enable the publish button. And it shows like this: ![enter image description here]( And I want it to be displayed like this after I make a change from my custom customizer control **which is an input not linked to the customizer** : ![enter image description here]( How can I enable the disabled publish button from my custom control when I change something with it? Thanks.
Just set the `saved` state to `false`: wp.customize.bind( 'ready', function() { wp.customize.state( 'saved' ).set( false ); } );
stackexchange-wordpress
{ "answer_score": 2, "question_score": 0, "tags": "theme customizer, publish" }
The best way to store variable across different widgets The front page of my site building with set of widgets. Each widget shows the rows with posts for some criteria. I want to exclude duplicate posts across different widgets. The simplest way comes to mind is to use global variable. For example: global $exclude; $query = new WP_Query([ 'posts_per_page' => publish, 'post__not_in' => $exclude ]); $exclude = wp_list_pluck( $query->posts, 'ID' ); I want to find better way to do this job. I've thought about `wp_get_cache`, but it seems that it is not what I want.
Unfortunately no one answers my question so I will show my way to solve this problem. I use public query vars with `get_query_var` and `set_query_var` functions to set `widget__exclude` variable across all queries. Still not sure that it is the best way for this case but hope it helps somebody.
stackexchange-wordpress
{ "answer_score": 1, "question_score": 0, "tags": "wp query, post duplication" }
Resources won't load if not logged to cPanel after migration, cause? I migrated my wordpress site to my live site. As mentioned in the title my site will look bad if I visit it and I am ot logged in cPanel. Guess it means resources are not accessable to all users. How to make site resources accessable to all?
Looks like some of your assets are using ` links instead of your domain which is why they aren't loading. These might be hardcoded in your theme or you may want to check your `options` table in the database for `option_name` "siteurl" and "home" and make sure they are updated to use the right URL instead of `
stackexchange-wordpress
{ "answer_score": 1, "question_score": 0, "tags": "accessibility" }
Cannot figure out what element header color is in wordpress theme good people, I am trying to help out a local small business with setting up a simple Wordress site. I am trying to change the color of the header from blue to black and I was able to do part of it, but there are bits of it on the left and right that I can't find what ID or class they fall under in order to apply a custom CSS style: < If anyone could point me to the correct CSS ID or class or show me how to find them myself so that I could change them to black I would really appreciate it! Thanks much, Ricky
You can use your browsers **Inspector** via it's **Developer Tools** to hover-and-reveal the class andor id name(s) of all html elements on a webpage. ![inspector]( Here's some links to popular browsers and how to get started with the tool * < * < * < For your site, I believe css of #site-navigation { background: black !important; } will do what you're after
stackexchange-wordpress
{ "answer_score": 1, "question_score": 0, "tags": "themes, css" }
Generate an Email address from that of the Post Author In a theme I'm developing I would like to have a button with a mailto: href so that it when a user clicks on it, it generates the email address dependent on the post author. I've managed to get it so that the email subject is generated from the post title by simply using the the_title(); I can't seem to work out how to dynamically generate the email address though. I need to replace the "[email protected]" part that is hard-coded below to automatically be the post author's email that is registered in their user profile in the back end. I was looking at get_the_author_meta(); function, but this only seems to allow you to add a parameter for 'user_email' and then you have to manually add the user ID, which again is no use. <a href="mailto:[email protected]?subject=<?php the_title(); ?>">Apply</a> Any help would be amazing.
You can use `get_the_author_meta` function. You can learn more about it here: < Usage in your case: <a href="mailto:<?php echo get_the_author_meta('user_email');?>?subject=<?php the_title(); ?>">Apply</a>
stackexchange-wordpress
{ "answer_score": 4, "question_score": 1, "tags": "post meta, author, email" }
Bedrock WordPress Bedrock google analytics problem. * I have used **Bedrock** in one of my wordpress project. * But google webmaster search console display that the page is automatically redirects to the /web. Please suggest for the same to ignore redirect for the google analytic. Thanks in advance.
Check your .env file. It should be sth like this: WP_ENV=production WP_HOME= WP_SITEURL=${WP_HOME}/wp Also check that your DocumentRoot in Apache config points to /path/to/your/website/ **web** < You could also check in discourse from Roots for a problem like that: <
stackexchange-wordpress
{ "answer_score": 1, "question_score": 0, "tags": "redirect" }
Get param from shortcode in plugin function I am trying to get the variable passed in my shortcode so I can do a request with the id to a API. The shortcode looks like this: `[product id="2"]` In my function I want to do something with the "2". Code so far: function getSingleProduct( $attr ) { shortcode_atts( [ 'id' => '0', ], $attr ); // Do someting with the "2". do_request( 'GET', get_api_url() . 'api/product/' . "2" ); // This "2" comes from the shortcode } add_shortcode( 'product', 'getSingleProduct' );
If you have this shortcode: [product id="2"] Which is redered by this: add_shortcode( 'product', 'getSingleProduct' ); function getSingleProduct( $atts ) { shortcode_atts( [ 'id' => '0', ], $atts ); // Do someting with the "2". do_request( 'GET', get_api_url() . 'api/product/' . "2" ); // This "2" comes from the shortcode } You can get the shortcode params like this: add_shortcode( 'product', 'getSingleProduct' ); function getSingleProduct( $atts ) { // $atts is an array with the shortcode params // shortcode_atts() function fills the array with the // default values if they are missing $atts = shortcode_atts( [ 'id' => '0', ], $atts ); $id = $atts['id']; do_request( 'GET', get_api_url() . 'api/product/' . $id ); }
stackexchange-wordpress
{ "answer_score": 1, "question_score": 0, "tags": "plugins, shortcode, parameter" }
Stop unauthorised file access I am developing a plugin in which is admin only back-end. With a custom role which will be created at a later date, as for now it is just manager. I am trying to stop the access to everyone getting onto the page, e.g I have the issue where currently if you go to the link, in my case which is `127.0.0.1/wp-content/plugins/my-plugin/templates/admin-settings.php` it will show the page but without the css but I believe everything still works. I've done some research and found the `is_user_logged_in()` function but I don't know if I need to include this in every single file or if there is a global file that I can do this in? Obviously I know I can do a `require_once auth.php` but is there an easier way?
You can use this code on top of your file and apply your role condition if required : `if ( ! defined( 'ABSPATH' ) ) exit; // Exit if accessed directly` For more details follow this link and other one ! Hope this will help. For more details where to use
stackexchange-wordpress
{ "answer_score": 0, "question_score": 0, "tags": "plugin development, wp admin" }
Reusing content from front page on sub page I am trying to reuse content from my static front page in a different page template. But because my front page is static, I can not call it by page name. Is it possible to call the front page another way? Preferably not by ID! My code: <?php $my_query = new WP_Query('pagename=front'); while ($my_query->have_posts()) : $my_query->the_post(); $do_not_duplicate = $post->ID;?> /* The content I want from the front page content */ <?php endwhile; ?>
Using `get_option()` you can get the page that is assigned to the front page: $frontpage = get_post(get_option('page_on_front')); Or as you have it: $my_query = new WP_Query( array( 'page_id' => get_option('page_on_front') ) );
stackexchange-wordpress
{ "answer_score": 2, "question_score": 0, "tags": "wp query, frontpage" }
Widget - Store and update data What is the best way to store data? Database, cache, etc? I want to build a widget, which will show some data from API, but I don't want to call API every time, because of limits. I'd like to call API every 3 hours or once a day and store data from API and timestamp when API was called. How to do it? _Sorry, don't have a code to show. It's more theoretical question_
You probably want to look at using WordPress Transients as they can handle both the data and the timestamp/expiration. You can also check out The Deal with WordPress Transients by CSS Tricks which has some good info as well.
stackexchange-wordpress
{ "answer_score": 2, "question_score": 1, "tags": "widgets, api" }
Use get/the_post_thumbnail with Custom Size & Crop We know that `the_post_thumbnail()` outputs the thumbnail & that `the_post_thumbnail( array(100,100) )` outputs the thumbnail at a specified size. And we know that we can use `add_image_size( 'category-thumb', 300, 9999, $crop );` to add a custom image size which we can call using `the_post_thumbnail('category-thumb')` with scaling and cropping applied. Is there a way to use `the_post_thumbnail` to crop an image when it's displayed? `set_post_thumbnail_size` could help, but I'm asking specifically if there is a way to do this with `the_post_thumbnail` This is relevant: the_post_thumbnail scaling not hard cropping **( if nothing's changed the answer is no )**
No, there's not a way to do this by using `the_post_thumbnail()`, neither it's recommended. What you are looking for is cropping the images on the fly. This will cost heavy server resources, especially when you have a lot of images to work with. But in theory, to do so, you can make a script that takes an image as input, crops the image using PHP, and then returns the image data without saving the actual file. But again, it's expensive.
stackexchange-wordpress
{ "answer_score": 2, "question_score": 2, "tags": "post thumbnails, cropping" }
Wp Login redirect strips parameters from url **If i write** ` in the url address bar (to make the login page redirect to a specific page with parameters) and login. **I get** redirected to the right page but only with first parameter (` the other two parameters are stripped from the url. How can i solve that? _Btw - the parameters are acceptable on this site (set in the functions file with`add_custom_query_vars` so that's not the problem)._
I think you should encode the & to avoid potential conflicts:
stackexchange-wordpress
{ "answer_score": 1, "question_score": 2, "tags": "redirect, parameter, query string" }
A shorter way to automatically update WordPress? This is how I started to update WordPress daily: cat <<-"CRON_DAILY" > /etc/cron.daily/nses_cron_daily for dir in /var/www/html/*/; do cd "$dir" && /usr/local/bin/wp plugin update --all --allow-root; done for dir in /var/www/html/*/; do cd "$dir" && /usr/local/bin/wp core update --allow-root; done for dir in /var/www/html/*/; do cd "$dir" && /usr/local/bin/wp theme update --all --allow-root; done chown www-data:www-data /var/www/html/* -R find /var/www/html/* -type d -exec chmod 755 {} \; find /var/www/html/* -type f -exec chmod 644 {} \; CRON_DAILY chmod +x /etc/cron.daily/nses_cron_daily I create the file with the heredocument, change permissions, and run daily. Is there a shorter, pluginless way to update (less rows, hahaha)? ## Update I didn't change basically anything inside `wp-config.php` besides database credentials.
If you have this statement (by default) in your wp-config file define( 'WP_AUTO_UPDATE_CORE', true ); Then WP core files are automatically updated for you. This assumes that you have traffic to your site (if nobody ever visits your site, the updates won't happen.) So your solution is actually causing more work by the server, and is sort of redundant and repetitive. By default WP will check for core updates all on it's own.
stackexchange-wordpress
{ "answer_score": 2, "question_score": 0, "tags": "updates, wp cli, linux" }
Custom taxonomy link automatically removing query string and re-directing Example: < is automatically redirecting to: < This is making it difficult to sort by multiple categories: < and sorting by multiple custom taxonomies. Any idea why it would be auto re-directing? I've disabled all plugins and it still does it. Thanks
WordPress uses the `redirect_canonical` function in order to ensure that URLs are properly following the current permalink structure: < The function is hooked to automatically run on the `template_redirect` filter. In order to remove it, you need to add the following snippet to your theme or plugin: `remove_filter( 'template_redirect', 'redirect_canonical' );` Keep in mind that this will allow a single page (in this case taxonomy index) to have multiple URLs, which is not good for SEO, because the following URLs will show the same content: * < * < WordPress will also not handle < automatically, since its base logic only works with a single taxonomy. The best way to approach this issue would be to use custom rewrite rules and to introduce a new rewrite/query tag, for example `categories`, instead of the default `categoryname`. This however, is a topic that cannot be explained quickly and requires some research first.
stackexchange-wordpress
{ "answer_score": 1, "question_score": 0, "tags": "custom taxonomy, redirect" }
Is Postfix required for WordPress contact forms in general? If I remember correctly, I could get data from `ContactForm7`, for example, into my personal Gmail account, without doing `apt-get install postfix -y`, though I might be wrong and I did install it. I don't have a ready testing environment so I can't confirm now, hence my question: Is Postfix required for WordPress ContactForms in general?
You don't need Postfix if you use an SMTP plugin like, for example, WP Mail SMTP. Such kind of plugins can send email from your Google account via SMTP. I have just checked it by stopping postfix and successfully sending an email via WP Mail SMTP. If no SMTP plugins are activated on your site, you definitely need system transport, which can be Postfix or another mail transfer agent (MTA) on Linux. Postfix also can send your emails using your Google account as a relay.
stackexchange-wordpress
{ "answer_score": 2, "question_score": 0, "tags": "email, contact, linux, smtp" }
Where I can find a list of Wordpress security risks? I'm working on one project where I need to find a list of different security risks or malicious codes which were used by hackers nowadays or in past. I can go and search one by one, but it will take a lot of time to gather a decent list of it. So, does anyone know where should I search or if someone gathered something like that?
You can check the WPScan Vulnerability Database The vulnerabilities are classified in 'Wordpress', 'Plugins' and 'Themes' at the top bar, from 2014 on. Cheers
stackexchange-wordpress
{ "answer_score": 0, "question_score": 0, "tags": "hacked" }
getting attributes in a product loop I have looked at all the examples online for getting attributes from a product. It seems relatively simple, but I just can't get any results. I'm starting to think it is just not setup properly in the wp-admin. The code I'm using: $args = array( 'post_type' => 'product', 'product_cat' => $meal->slug, 'posts_per_page' => -1 ); $loop = new WP_Query( $args ); while ( $loop->have_posts() ) : $loop->the_post(); $attribute_value = wc_get_product_terms( get_the_id(), 'pa_calories' ); var_dump($attribute_value); echo '<div class="meal-products bottom col-md-6">' . get_the_title() . '</div>'; endwhile; I've tried other code snippets like `get_terms()` etc. but I keep getting empty strings or false. What am I doing wrong?
My naive problem was because I was not noticing the attribute wasn't being saved when I clicked save attributes. The reason it wasn't being saved was because I wasn't entering a value for the attrib.
stackexchange-wordpress
{ "answer_score": 0, "question_score": 0, "tags": "woocommerce offtopic" }
Allowing all/different file type uploads I've looked through a number of previously accepted answers, but none seem to work/apply to the latest versions of WordPress. I'm trying to allow `.rfa` file types to be uploaded to the media library. This is what I've found from a previous answer; function additional_mime_types($mime_types) { $mime_types['rfa'] = 'application/octet-stream'; return $mime_types; } add_filter('upload_mimes', 'additional_mime_types', 1, 1); How can I allow .rfa file types to be uploaded to the media library?
I had the same issue, it looks like WordPress isn't able to determine the correct MIME type for RFA files, so it defaults to: `'application/CDFV2-unknown'` Changing the MIME type to this fixed it for me. So it would be: add_filter( 'upload_mimes', function ( $mime_types ) { $mime_types['rfa'] = 'application/CDFV2-unknown'; return $mime_types; } );
stackexchange-wordpress
{ "answer_score": 2, "question_score": 0, "tags": "uploads, wp filesystem" }
How to turn off WooCommerce user registration and manually create accounts? I built an online store with WooCommerce. Now, I would like to disable WooCommerce user registration and register accounts manually. I want my store to be visible for everyone, but people should only be able to purchase something when they have an account that I created for them. How do I do this?
Just disable customer registration on WooCommerce->Settings->Accounts page. ![enter image description here]( if you want to prevent checkout for not logged in users, uncheck WooCommerce->Settings->Checkout->Enable guest checkout ![enter image description here](
stackexchange-wordpress
{ "answer_score": 6, "question_score": 3, "tags": "woocommerce offtopic" }
How To Hide Filters On Specific Categories with WooCommerce Products Filter(WOOF) I am trying to put filters on products categories and I tried WOOF-WooCommerce Products Filter on wordpress and I saw that the filters that I created on a specific category are sticked and on the other categories which I want to have different filters. Do you know how can I fix that with this plugin or can you recommend me a plugin that supports that feature or if it is possible in any way? Thank you
Try to use my plugin WOOF by Category. It was developed exactly for this task.
stackexchange-wordpress
{ "answer_score": 4, "question_score": 2, "tags": "plugins, woocommerce offtopic, e commerce" }
Network of multisites in Wordpress, create new site with all the contents of the main I started a project in Wordpress months ago, I have completely configured the website, design, content, templates etc ... Now I want to create a network of sites, I have configured it and launched it with this manual < but when I create a new site, the whole site is not duplicated, it's as if I installed Wordpress again, in the new created site. It is possible that I can create a new site by cloning all the data from the main website?
You can use Multisite Clone Duplicator plugin.
stackexchange-wordpress
{ "answer_score": 2, "question_score": 0, "tags": "multisite, network admin, multisite user management" }
Email Bounce Address I'm having a little issue with my SMTP. I use a plugin **WP MAIL** to manage the email configurations as it makes it easy to run in/outgoing emails without leaving unsent or stuck mails. Everything is working properly but the email shows this `[email protected]` as Bounce address which is not good for SEO plus it shows the username of my **WP** installation, which is not the best for the security.I'd really like to change that. Any idea to work this out? **PS** : `/home/Uxxxxxxxx/public_html/wp-admin/options-general.php` this is also shown from the received email. Any way to change this either? Thanks a lot everyone
That seems to be the configured SMTP server by your hosting. It might be possible to configure this if you have CPANEL included. If that's the case, take a look at this article. It explains how you can create your own SMTP address and use it for sending e-mails from your website. Alternatively, you can use another provider to send emails for you. I can recommend sending your emails with a SMTP provider like Sendgrid. You will need to signup, add CNAME records to your domain, and you can use for example mailing.example.com as your sender address. It offers a ton of features and Deliverability is great. With a plugin such as Post SMTP Mailer/Log this can be easily configured. Let me know if it helps you! Cheers..
stackexchange-wordpress
{ "answer_score": 1, "question_score": 1, "tags": "plugins, email, smtp" }
Why is WP_Mock not used instead of WP_UnitTestCase for writing unit tests by most plugins? For writing unit-tests, why do most plugins use `WP_UnitTestCase` instead of popular libraries like `WP_Mock`? The reason I am asking this is because WP_UnitTestCase doesn't seem to be a unit test case but integration test as it requires WordPress-test environment & make actual DB-calls to WordPress-test-db? While WP_Mock mocks all WP functions and you can test class in isolation(which is also the definition of unit tests). Is there anything I am missing out here?
One is official, the other one is a 3rd party library by 10up, so people tend to use the official `WP_UnitTestCase` There is no right or wrong choice however, use the library you prefer > Is there anything I am missing out here? No, some tests that core conducts require a temporary WP install to fully test. Some older APIs weren't built for test isolation. As such, `WP_UnitTestCase` and `WP_Mock` are both capable of unit tests, but `WP_UnitTestCase` is also used for other kinds of tests. For your purposes as a plugin or theme author though, that particular information is irrelevant, and both are options. It really is up to your personal preference
stackexchange-wordpress
{ "answer_score": 5, "question_score": 2, "tags": "plugin development, testing, unit tests" }
Wordpress Admin Login Redirect Problem I have a site that we have developed that we have just moved live. Another company has the domain name currently so they are redirecting to our IP and DNS. The website works fine and all forms are working but the admin login form is getting a 'too many redirects' error when trying to load. We run our development sites from the same server, but on a subdomain and that is working fine. I've tried removing htaccess and plugins, replacing all the files again, replacing the database and it still doesn't work. I am at a loss to what the problem could be caused by? This is a standard WP site, not multi-site, and is running on HTTPS. Any ideas? Thankyou in advance!
solved this issue in the end. i removed all the files deleted the cpanel account, and re did everything. This seemed to solve the problem this time!
stackexchange-wordpress
{ "answer_score": 0, "question_score": 1, "tags": "admin, redirect, login" }
Enable Comments Box On Custom Post Type The wordpress theme I'm using doesn't support comments on one of its custom post types (Shows) and I've been trying to enable them. I added the code below to single-shows.php (copied from shows.php) and it shows previous comments that were already there but doesn't show the comments box to post new comments. I also modified the "supports" for the custom post type to include comments. I checked discussion settings and checked screen options - there's comments but no discussion checkbox. <?php if ( comments_open() || '0' != get_comments_number() ){ ?> <hr class="qt-spacer-m"> <?php comments_template(); ?> <?php } ?> The site is this. Here's an example show with old comments appearing: Here's a post that has the correct comment box and all: Hope someone can help! This is key to launching the site...
For anyone who is having a similar issue, the problem was that the child theme was not registering the custom post type. I had to change the "supports" there for it to work. Not ideal but it's fixed.
stackexchange-wordpress
{ "answer_score": 0, "question_score": 1, "tags": "posts, comments, customization" }
Why do some sites show themes/"themename" as the only theme? While inspecting some sites built with WordPress, I noticed that in some cases the themes folder is named - themes/"themename". And instead of there being multiple themes inside this folder, there is simply the root of the single theme. Is this common practice when only one theme is being used? Or is there something I'm not noticing. See below screenshot for reference. ![Example](
You can't remotely inspect site's files and directories. That's not what's happening here. The browser inspector is just reconstructing the structure based on the URLs of resources that it is loading. The browser sees that `/wp-content/themes/themename/style.css` is being loaded, and `/wp-content/plugins/plugin/style.css` and assumes that there must be `/wp-content/themes/` and `wp-content/plugins/` directories. So it creates a file browser for you based on this structure. This also means that it is only showing files that the browser is loading. This is not a full (or necessarily accurate) view of the actual file structure on the server. And the reason that `themes/webdesingsun` is being shown as a single folder, is simply because the browser is only loading resources from one directory in `/themes/`, so it's saving you the trouble of having to expand the only folder in `/themes/`.
stackexchange-wordpress
{ "answer_score": -1, "question_score": -2, "tags": "theme development, themes" }
How to manage a music library in wordpress I need to make a music library which will primarily be sorted by artists. I'll need a database to hold all the music titles, artist, genre etc. I'll need some sort of backend language to manage the library when users are interacting with it. I'm kind of new creating this sort of website, I'm having trouble piecing all the pieces together for this, I've only managed static websites before. I need guidance or advice on which technologies to use to make a standard music library which is primarily sorted by artist.
You can register a custom post type called `songs` or `albums`. * Learn more about custom post type registration here: < * More info on Post Type: < You can register custom taxonomies in WordPress as well. * Learn about taxonomies here: < * Learn about taxonomy registration here: < You can then associate `songs` or `albums` with an `artist`. This can be achieved quite easily by using the two following tools. * < * < Adding the output to your `functions.php`. If you want to query your new post type you can use `WP_Query`. Read more on it here: < Simple tool to generate a WP_Query - <
stackexchange-wordpress
{ "answer_score": 1, "question_score": 0, "tags": "media library, sort" }
Remove "Browsed by Category" from Category Page I want to remove "Browsed By Категорија: ..." from my category pages, but I don't know how. Web site is: < Theme is nisarg. Thank you in advance.
Add to the style.css (< of your theme the following: .category h3.archive-page-title { display: none; }
stackexchange-wordpress
{ "answer_score": 1, "question_score": 0, "tags": "categories" }
Translation plugin to translate another plugins I have installed several plugins, but there are a lot of, which doesn't support my language. I found solutions, which supports to write multilingual content, but can't handle language of plugins or maybe translate it automatically with help of some webservice.
Poedit is the way to go fro translating most of your plugins. WPMl is doing quite a good job, though, at parsing plugins and themes strings for translation purposes. You should give it a try.
stackexchange-wordpress
{ "answer_score": 1, "question_score": 0, "tags": "plugins, customization, multi language" }
How to redirect a wrong search on my wordpress website to the error 404 page? For example, my wordpress website is `www.example.com`. If I type `example.com/abcdef` or any other url that does not exist, it redirects to my **custom 404 page** without any issues. However, when I search something, the url changes `to www.example.com/?s=abcdef` and it shows wordpress's default 'Nothing Found' page. Is there a way I can redirect a wrong search's to my **custom 404 page** or can I change wordpress 'Nothing found' page? Thanks
A search shows the search template regardless of whether or not there are any results, which is either `search.php` or `index.php` if that template doesn't exist. If you want to load an entirely different template, you can use the `search_template` filter. Assuming your theme's 404 template is `404.php`: function wpd_search_template( $template ) { if( ! have_posts() ) { $template = locate_template( array( '404.php' ) ); } return $template; } add_filter( 'search_template', 'wpd_search_template' );
stackexchange-wordpress
{ "answer_score": 2, "question_score": 0, "tags": "redirect, 404 error" }
Query how many items to show in shortcode I am building a shortcode that will display my custom post type (portfolios). I want to add another option to add how many items to show. This is what I have for now, but it shows all items, and I need to add a 'items' shortcode_att but not sure how to call it in the query later. Thank you!! add_shortcode( 'type_portfolio', function( $atts, $content = null ){ $atts = shortcode_atts( array( 'column' => '3', 'category' => '0' ), $atts); extract($atts); $args = array( 'posts_per_page' => -1, 'post_type' => 'fen_portfolio' ); if( $category > '0' ){ $args['tax_query'] = array( array( 'posts_per_page' => -1, 'taxonomy' => 'cat_portfolio', 'field' => 'term_id', 'terms' => $category ) ); } $portfolios = get_posts( $args );
add_shortcode( 'type_portfolio', function( $atts, $content = null ){ $atts = shortcode_atts( array( 'column' => '3', 'category' => '0', 'ppp' => -1 ), $atts); extract($atts); $args = array( 'posts_per_page' => $ppp, 'post_type' => 'fen_portfolio' ); if( $category > '0' ){ $args['tax_query'] = array( array( 'posts_per_page' => -1, 'taxonomy' => 'cat_portfolio', 'field' => 'term_id', 'terms' => $category ) ); } $portfolios = get_posts( $args );
stackexchange-wordpress
{ "answer_score": 1, "question_score": 1, "tags": "posts, shortcode, query" }
How get Data form wordpress database as array not stdclass? Guys I tried this code: $wpdb->get_results(sprintf("SELECT ID FROM wp_posts WHERE ID = '%s' AND post_type = 'edd_payment'",$id)); it returned an std class How can I get data form db as array not stdclass?
See here $wpdb->get_results ` $wpdb->get_results($query,ARRAY_A ); `
stackexchange-wordpress
{ "answer_score": 1, "question_score": 0, "tags": "database" }
Get the Current Page Slug-Name I want to Retrieve the Current Pagename , Inside my Breadcrumb , i tried many ways to get the idea work , but unfortunately they didn't work e.g : <?php wp_title('true'); ?> $pagename = get_query_var('pagename'); if ( !$pagename && $id > 0 ) { // If a static page is set as the front page, $pagename will not be set. Retrieve it from the queried object $post = $wp_query->get_queried_object(); $pagename = $post->post_name; }$slug = basename(get_query_var('pagename')); for more Clearly Question , My Idea is to get the pagrname for the breadcrumb bootstrap , i mean lik this ' Home / PageName / Postname(if it navigated) .
Assuming you're doing this from inside the Loop, you can get it this way: global $post; $page_slug = $post->post_name; Then just use `echo $page_slug;` in the location(s) you which to have it displayed. For outside the loop, you will need to use different code: $the_page = sanitize_post( $GLOBALS['wp_the_query']->get_queried_object() ); $slug = $the_page->post_name;
stackexchange-wordpress
{ "answer_score": 3, "question_score": 0, "tags": "pages, slug" }
if I create 'front-page.php', then how do I link to post index? I want to have a custom front page and a blog page. So I created the `front-page.php` file, which will include my custom markup. I don't want to have blog post index on my front page, so I created `home.php` to feature blog posts index. How do I link to the blog page in this case?
Since WordPress 4.5 you can use `get_post_type_archive_link( 'post' )` to link to the page containing the blog posts. Depending on what you've set under Settings -> Reading, this will be either the front page, e.g. `example.com/` or a specific page like `example.com/news/`. `home_url( '/' )` always points to the front page.
stackexchange-wordpress
{ "answer_score": 3, "question_score": 1, "tags": "posts, links, frontpage" }
How to log plugin errors to plugin error_log file How can errors, specific to a given plugin, be logged to an `error_log` file contained within the plugin root folder itself? **Examples:** * Syntax errors * Database errors * Compatibility errors * PHP fatal errors * Ajax request errors Similar to the `/wp-content/debug.log` file enable when `WP_DEBUG_LOG` is defined as `true` in the `wp-config.php` file ( _albeit specifically for plugins with its concerns separated from any other general error unrelated to the plugin itself_ ). **Research:** **Debugging Plugins** section in the official documentation of the Codex refers to using 3rd party plugins to debug 3rd party plugins. **Don’t Develop Without Debugging** by Smashing Magazine refers to site-wide general debugging. **Plugin Handbook** appears to layout no specific guidelines.
By setting the second argument to 3 for `error_log`: $pluginlog = plugin_dir_path(__FILE__).'debug.log'; $message = 'SOME ERROR'.PHP_EOL; error_log($message, 3, $pluginlog); <
stackexchange-wordpress
{ "answer_score": 9, "question_score": 4, "tags": "plugin development, customization, errors" }
Only get post types based on support I am trying to retrieve a list including both builtin and custom post types: $post_types = get_post_types(array( 'public' => TRUE, ), 'objects'); The above almost works, but I would like to exclude the `attachment` from this list, only returning post types with specific support such as `editor`, `title` and `thumbnail`. Is this possible?
I found out that `get_post_types_by_support()` seems to be the solution to get the desired result: $post_types = get_post_types_by_support(array('title', 'editor', 'thumbnail')); The above will return `post`, `page` and any custom post type that supports `title`, `editor` and `thumbnail`. Since this will also return private post types, we could loop through the list and check if the type is viewable at the frontend. This can be done by using the `is_post_type_viewable()` function: foreach ($post_types as $key => $post_type) { if (!is_post_type_viewable($post_type)) { unset($post_types[$post_type]); } }
stackexchange-wordpress
{ "answer_score": 9, "question_score": 9, "tags": "custom post types, post type support" }
Update User Role I'm developing an plugin that adds an new user role (client role, for instance). This role only extends the admin role for now. add_role( 'client', __('Client'), get_role('administrator')->capabilities ); Now i wan't to release an new version of the plugin that update the client capabilities and remove the `install_plugins` capability. Roles are persistent, so i can't just update my `add_role`. **My question is:** how can i manage an custom role, updating it's capabilities?
Off the top of my head, you should be able to do something like this: $role = get_role( 'client' ); if ( $role && $role->has_cap( 'install_plugins' ) ) { // Role not updated yet, so update it. $role->remove_cap( 'install_plugins' ); } `get_role()` returns a `WP_Role` object on success and `WP_Role::remove_cap()` calls `WP_Roles::remove_cap()`, which directly updates the option in the database. The `$role->has_cap()` check ensures that the code isn't run twice. Running this in a function hooked to `init` should suffice. Ideally you'd have a database version option for your plugin which you could use to run some code exactly once per plugin update. Otherwise your code is executed again every time someone manually adds the `install_plugins` capability to your role again. That's not necessarily bad, but it could be prevented :-) Code reference: * `get_role()`. * `WP_Role` * `WP_Roles`
stackexchange-wordpress
{ "answer_score": 2, "question_score": 1, "tags": "plugins, user roles, capabilities" }
Will loading too many ACF Fields cause slow down? * I work on a website which uses about 5-8 ACF fields on almost every page (an ACF Fan!). The count goes up to 10-12 fields in the `single.php` of my CPTs. * I call the ACF fields directly using the `the_field` / `get_field` functions and have used flexible content and hierarchical repeater fields etc. 1. How much impact would this make on the performance of my website? 2. How to make them more efficient, and consume less server. 3. Does using some particular fields over the other have a performance advantage?
This is hard to answer. The (experienced) performance depends on how powerful your server is, how much simultaneous users are accessing your site etc. With a dozen ACF-fields, you will most likely not experience any significant performance loss. A typical request to a WP page will often result in dozens of database queries, your 10 additional queries will hardly matter. If you are worried about performance, you should look into caching the response completely. There are multiple plugins for that, or you could use servers like nginx or varnish that sit in front of your webserver and cache some responses.
stackexchange-wordpress
{ "answer_score": 1, "question_score": 1, "tags": "custom field, advanced custom fields, performance" }
Insert Code into Header Only on Blog Posts Is there a way to put some code into the header but have it load only on blog posts? Maybe a plugin or a piece of code that could help me accomplish this?
Yes. In your `functions.php` file, add something like the following: function my_post_header_function() { if( is_single() ) { // Your Code Goes Here } } add_action( 'wp_head', 'my_post_header_function' ); What this will do is execute this when `wp_head()` is fired. It will see if you're on a single post (NOTE: This will _not_ work on pages or attachments) and if you are, it will execute the code you want to put.
stackexchange-wordpress
{ "answer_score": 1, "question_score": 0, "tags": "headers" }
Look for a file in a theme before loading from plugin I am developing a plugin and I would like users to be able to override specific files from their theme. For example: I am including the file `people.php`, located in: `/plugins/my_plugin/view/people.php` Anyone can add a file to their theme / child theme as well, by putting it in this location: `/themes/my_theme/my_plugin/view/people.php` I know that Woocommerce supports this functionality. What do I need to do?
Woocommerce use locate_template for checking if file exists in theme or not
stackexchange-wordpress
{ "answer_score": 1, "question_score": 0, "tags": "plugin development, filesystem" }
Google webmaster duplicate url issue with /page/01 /page/400 I am at the intermediate level in WordPress development. I am facing a problem with URLs. Google webmaster is showing me duplicate pages and error pages URLs like `www.mywebsite.com/page/01` to `www.mywebsite.com/page/400`. When I type `www.mywebsite.com/page/01`, it redirects me another page with posts and pagination. I tried editing the `.htaccess` to disable this but to no avail. I don't know how to search this problem via google and I need a solution on how can I disable these types of URLs.
if someone find this helpful. i research and find solution using .htaccess rules to solve these errors maybe it is temporary but it fixed my problem. i redirect all these type of errors to home page using below code: <IfModule mod_alias.c> RedirectMatch 301 /page/[0-9]{2,} RedirectMatch 301 /page[0-9]{2,} </IfModule>
stackexchange-wordpress
{ "answer_score": 0, "question_score": 1, "tags": "permalinks" }
Create a global variable for use in all templates I used following code function userinfo_global() { global $users_info; wp_get_current_user(); } add_action( 'init', 'userinfo_global' ); in a file `users.php` , this file are call in inside `funtions.php`. in template file I have `<?php echo $users_info->user_firstname; ?>` , but no working.. I want to do global `wp_get_current_user();` You know why?
You'll also have to fill the variable, e.g. function userinfo_global() { global $users_info; $users_info = wp_get_current_user(); } add_action( 'init', 'userinfo_global' ); And you should then be able to use $users_info everywhere in global context. Keep in mind that some template pars (header.php, footer.php, those used via `get_template_part`) are not in global scope by default, so you'll have to use `global $users_info;` in those files before accessing the variable.
stackexchange-wordpress
{ "answer_score": 5, "question_score": 4, "tags": "php, functions, users, globals" }
How to disable a network enabled plugin on all sites, excepting on one? I would like use a plugin only on my network home site. Here is the converse of my question: wordpress.stackexchange.com There is the solution this: add_filter('site_option_active_sitewide_plugins', 'modify_sitewide_plugins'); function modify_sitewide_plugins($value) { global $current_blog; if( $current_blog->blog_id == 2 ) { unset($value['akismet/akismet.php']); } return $value; } How to modify this code, that the $value plugin should be disabled on every subsites (automatically also on subsequent sites), expect on the $current_blog?
So the code is for one site, and you want it to be for all except one. You need to change the **==** part to **!=** in order to do this. This way instead of running the code inside the _if_ on the site with ID 2, it will run on all sites except the one with ID 2. But I don't know why you would do this, since you can activate a plugin only on one site by just activating it from its dashboard (you do not need to network activate it).
stackexchange-wordpress
{ "answer_score": 0, "question_score": 1, "tags": "multisite" }
How to create a network using a command line script? I would like to run UI automated tests for my WordPress plugin. I am using Docker to run a WP instance and it runs my tests, that is fine. I am using `wp-cli` to install and config a testing site. I would also like to run the test suite on multisite. For that, I need to setup a network. I know how to install a multisite network manually, but I need a command which I add to my Dockerfile. So my question is: Is there a way how to create a multisite network using command line script?
Since you're already using WP-CLI, I recommend you to use the `wp core multisite-install` command to set up your network installation. When you check out the documentation you'll see that it's pretty straightforward. Here's the example from the docs: $ wp core multisite-install --title="Welcome to the WordPress" \ > --admin_user="admin" --admin_password="password" \ > --admin_email="[email protected]" Single site database tables already present. Set up multisite database tables. Added multisite constants to wp-config.php. Success: Network installed. Don't forget to set up rewrite rules. You can perfectly use this command to set everything up in your Docker environment.
stackexchange-wordpress
{ "answer_score": 1, "question_score": 1, "tags": "multisite, wp cli, testing, docker" }
Can you use admin pages functionality on the frontend of your site I posted a similar question on stack Overflow and have it gotten a reply. I want to use the woocommerce reports on the front of my site, but I don't understand the difference of how an admin page works versus the front of the site... to give this question a little more value for another reader I'll broaden the question that should solve my problem which is Can admin functions be moved or access to the front end of a WordPress site?
Admin and front end are just semantics which are probably more appropriately should be called restricted access and non restricted access. There is no magic involved in the "admin" side and you can use the same function calls to show the same information on the front end. In practice, since you will most likely want the user to login to get access to the information, it will be probably easier to modify the admin to let the give the user access, unless you are creating your own admin screens for users which are not the site admins.
stackexchange-wordpress
{ "answer_score": 2, "question_score": 2, "tags": "functions, woocommerce offtopic" }
RSS and Post edits I have a blog with "dynamic content" (one type of post data is changing (the date, too) based on some circumstances). If I give the feed to one RSS feeder and one chatfuel based chatbot will the changes also "shown" (for example if a post was published in 2th of January and today the date was changed to 15th of January) will it move in the post order in the RSS feeds, too?
It should since the RSS feed is based on the current instance of `WP_Query`. However by default WordPress has a longer interval for updating the RSS feed's cache. IIRC, it's about 12 hours. So if you make a change at 6am, the RSS feed won't reflect that until 6pm. You can change this with the following code in your `functions.php` file or, even better, as a plugin. function rss_update_feed() { return 60; //Time in seconds } add_filter( 'wp_feed_cache_transient_lifetime', 'rss_update_feed' ); What this code does is sets the refresh time to 60 seconds. You will want to set it to something a bit more reasonable though. I only used 60 seconds as an example but you do not want to have your server keep doing unnecessary refreshes.
stackexchange-wordpress
{ "answer_score": 1, "question_score": 0, "tags": "rss" }
How Can I Have A URL Changed Based on the Originating URL? This is a followup to my question, "How can I have two different urls for the same page that load two different templates?" Assuming I implement Milo's answer (registering a new rewrite endpoint, load a different template if endpoint is present), how can I then have links within the page rewritten on the fly to include the endpoint (e.g. app-view). The page the initial endpoint would be added to is: < Based on Milo's instructions using the rewrite endpoint and page template filter, the url I'd pass from the mobile app would be: < Now on this page say I click on one of the series, e.g.: < Problem is this will load with the regular template, not the template created particularly for the mobile view. So somehow I have to pass on to this page that it should be displayed in app-view. So the actual URL the individual should be redirected to would be: < In what way could one accomplish this? Thanks!
You can use the `page_link` filter with the same logic as the `page_template` filter in the other answer. If the endpoint query var is set, then any link to a page gets the `app-view/` appended: function wpd_page_link( $link, $post_id ){ global $wp_query; if( isset( $wp_query->query_vars['app-view'] ) ){ return $link . 'app-view/'; } return $link; } add_filter( 'page_link', 'wpd_page_link', 10, 2 );
stackexchange-wordpress
{ "answer_score": 1, "question_score": 2, "tags": "filters, templates, url rewriting, page template, mobile" }
ping_status in JSON REST API **What is ping_status in JSON schema of wordpress REST API? And what is it's use cases?**. The official documentation is not much explain about it - Posts|REST API Handbook.
According to WordPress Codex, pings tells **Whether the current post is open for pings.** In human words, **A ping is a “this site has new content” notification** that invites search engine bots to visit your blog. For more info, have a look at this blog article.
stackexchange-wordpress
{ "answer_score": 2, "question_score": 2, "tags": "posts, rest api, json, plugin json api" }
How to call WordPress function other files Hi All i am in word Press I have successfully integrated WordPress membership plugin and all data of users is saved in database. Different users have different levels. My major task is to disable some website button according to user levels. so i try to Get user id in report.php using require_once("/wp-load.php"); $current_user = wp_get_current_user(); **But it gives internal 500 error** my directry structure is /myproject/wp-content/themes/fount/myfolder/report.php
Let's say that _wp-load_ is in the folder **/myproject/** of your `/myproject/wp-content/themes/fount/myfolder/` tree. From **/myfolder/** you would access it with `"../../../../wp-load.php".`
stackexchange-wordpress
{ "answer_score": 0, "question_score": 1, "tags": "plugins, php, wp query, functions" }
Add new MCE button for toggle specific cell background color I'm using tables as a calendar for free dates in my schedule. You can see free dates here. < Now I'm using the Table->Cell->Cell Properties->Advanced->background I want to have a button (or two) for turn on/off the green background in the selected cell. Is it possible? Thank you for any kind of help.
I have found a great tutorial about making a custom button to the tinymce. < You can just follow this guide and copy all of it. Don't forget to activate your new plugin in the plugin menu (in admin panel). Then you can just change the code inside index.js and especially in the `ed.addCommand("green_command", function() { ` For making the background of the selected cell toggle (on/off) you just change the code like this: `//button functionality. ed.addCommand("green_command", function() { ed.formatter.register('termin_format', { selector: 'td', styles: { backgroundColor: '#adf2a7'}, }); ed.formatter.toggle('termin_format'); });
stackexchange-wordpress
{ "answer_score": 0, "question_score": -1, "tags": "tinymce, table, buttons" }
WP_Query result in form of Rest API results This is simple posts result array. $query = new WP_Query( array( 'post_type' => 'post' ) ); $posts = $query->posts; // returns simple array of data Is there a way to get the results from wp-json/wp/v2/posts/?_embed without making extra request to server to pull json and then decode to php array? Looking for something like that: $posts = $query->rest_posts(); // for example ??
I think we can simplify it with: $request = new WP_REST_Request( 'GET', '/wp/v2/posts' ); $response = rest_do_request( $request ); $data = rest_get_server()->response_to_data( $response, true ); by using `rest_do_request()`.
stackexchange-wordpress
{ "answer_score": 4, "question_score": 6, "tags": "wp query, json" }
renaming an admin menu item with decimal array index number I am trying to rename a menu item on my administration dashboard. Using the $GLOBALS['menu'], I have found the following array indexes > [26.0648] => Array ( [0] => M.E. Calendar ... and > [26] => Array ( [0] => Products ... After using the following code: global $menu; global $submenu; $menu[26.0648][0] = 'Event Calendar'; The result is that the "M.E. Calendar" item has not changed, whereas the Products item has changed to > [26] => Array ( [0] => Event Calendar [1] => edit_products [2] => edit.php?post_type=product Is there a way I can rename the menu item with the decimal array index number? Thanks.
You have to use a string as key: $menu['26.0648'][0] = 'Event Calendar'; If you write the key as a number, it will truncate the decimal to an integer, so 26.0648 will be truncated to 26.
stackexchange-wordpress
{ "answer_score": 7, "question_score": 3, "tags": "php, menus, admin, admin menu" }
How do I make the main page be the blog page and not a separate "home" page? If you go to www.TwistedTalesOfTimmy.com you will be at the main page. It is a web comic strip with Comic Easel installed. You can get back to this page anytime you click the logo at the top. However, if you click HOME in the menu, it takes you to a separate home page. I want the main page to be the home page. Additionally, I'm trying to make this home page the blog page as well.
There are two possible settings for this in WordPress. **Option A** Your front page (< is **dynamic** and shows the latest blog posts. **Option B** Your front page (< is **static** and points to a regular page in WordPress. There is another page (e.g. < that shows the latest blog posts. * * * You can switch between both options under Settings -> Reading in your WordPress admin: ![enter image description here]( Choose what's right for you. After that, you can edit the navigation menu under Appearance -> Menus or Appearance -> Customize to make sure the "Home" link really points to the home page (front page).
stackexchange-wordpress
{ "answer_score": 3, "question_score": 1, "tags": "homepage, blog" }
WordPress Customizer checkbox default not working I am having a problem with the WordPress Customizer checkbox default value. No matter what I put in the default value, but the checkbox is always checked in the theme customizer. $wp_customize->add_setting( 'swastika_social_youtube', array( 'capability' => 'edit_theme_options', 'default' => 'false', 'sanitize_callback' => 'swastika_sanitize_checkbox', ) ); $wp_customize->add_control( 'swastika_social_youtube', array( 'type' => 'checkbox', 'section' => 'social_settings_section', 'label' => __( 'Show Youtube Icon', 'swastika' ), ) ); And here is how I am showing icon <?php if ( true == get_theme_mod( 'swastika_social_youtube', false ) ) { ?> <a href="#"><i class="fa fa-youtube-play" aria-hidden="true"></i></a> <?php } ?> ![enter image description here]( Please Help Me
Your default of `'false'` is actually a string, which evaluates to true because it's not empty. Use plain `false`, without the quotes.
stackexchange-wordpress
{ "answer_score": 0, "question_score": 1, "tags": "theme customizer" }
Should our pages be posts? We are posting a lot of content for our community (about 3 pages a day). All the content that is being published is created in pages. My question is this: is there any difference between 'pages' and 'posts' when it comes to volume? Dos WP prefer posts over pages for speed or efficiency? Thanks
Both pages and posts are identical internally. Pages are posts of type `page`, and posts are posts of type `post`. It's just a column in the posts table that determines the difference. Similarly, items in the media library are posts of type `attachment`, menu items in a menu are posts of type `nav_menu_item`, etc etc So they're all as fast as eachother. The speed differences come when you start querying for them. E.g. Showing a list of all pages in a column will be expensive if you have 1000 pages. Likewise, the same is true of posts. I mention this because the parent page dropdown in the edit page screen will do this, and it's the one place lots of pages will rear its head as a performance problem. My advice is to stop repurposing pages, and instead use a custom post type for your content, and a custom taxonomy to organise/structure them. There's no need to have pages that are purely to act as parents for the URL, or to group things. Thats what categories/tags/custom tax are for.
stackexchange-wordpress
{ "answer_score": 5, "question_score": 2, "tags": "posts" }
Get Post ID by Content I am trying to get a post ID by it's post content. I have a custom post type of **'membership'** which has post_content that looks like this... {"member_id":33} I am trying to get the ID of this post by searching for **{"member_id":33}** Am I best off doing this using an SQL statement or is there a better way to do it using WordPress functions?
WordPress has a handy function called `post_exists()` which allows you to find an existing post by its title, content, and/or date. It returns the post ID on success or 0 otherwise. In your case, you can use `$post_id = post_exists( '', '{"member_id":33}' )` to find the post you're looking for. Note: That function doesn't check the post type so you'd need to do that separately or roll your own function if it's necessary. I doubt it though that you have other posts with the same content :-)
stackexchange-wordpress
{ "answer_score": 9, "question_score": 6, "tags": "custom post types, sql, content" }
Export list of users with first and lastname in WP-CLI I want to export a CSV file with a list of my Wordpress site users with WP-CLI. I can do this but I'm getting my users first and lastname together in one column (display name), I would like to get them each in their own column. Is there a way to do this? I can't find first and lastname as available options in the docs that lists optional fields.
According to the documentation for `wp user list`, the `fields` argument accepts any valid `WP_User_Query` field. Thus, you can simply use `wp user list --fields=first_name,last_name --format=csv` to list all users with their first and last names. Of course you can add any other fields that you need. Note: You can get the documentation for each command using the `--help` flag, where things like that are mentioned.
stackexchange-wordpress
{ "answer_score": 4, "question_score": 4, "tags": "wp cli" }
add WordPress script to page conditionally by category I use a plugin "Post Tags and Categories for Pages" which adds categories to pages. My intention is to enqueue an external script on a page, only when it's needed. So if I assign a page to a category, only that page gets the script loaded. I have this hook: to function my_conditional_enqueue_script1() { global $page; if ( is_single() && in_category( '19' ) ) { wp_enqueue_script( '/members/application/cart/views/public/js/cart.js' ); } } add_action('wp_enqueue_scripts', 'my_conditional_enqueue_script1'); Seems like it should work, but it doesn't. Any suggestions? Or, is it more advisable to maybe add the script on a page my using short-codes (wrap the hook in plugin somehow)? Thanks for any help with this.
`is_single()` doesn't work for the `page` post type, use `is_page()` instead. You're also missing the first argument for `wp_enqueue_script`, the script handle. Source should be the second argument. function my_conditional_enqueue_script1() { if ( is_page() && in_category( 19 ) ) { wp_enqueue_script( 'my-cart-script', '/members/application/cart/views/public/js/cart.js' ); } } add_action('wp_enqueue_scripts', 'my_conditional_enqueue_script1');
stackexchange-wordpress
{ "answer_score": 1, "question_score": 0, "tags": "wp enqueue script" }
GravityForms inside Gantry4 won't display Implementing GravityForms inside a the Gantry4 Template works fine until inserting the form to a page. The form (which includes conditionals) is not displayed in the public view of the page. After 7 hours of research seems the problem comes from the theme (Gantry4) as changing it for another theme does display the form, but support team for GravityForms don't give any direct solution, they rather recommend to change the theme. Trying to change the theme to Gantry5 seems to be a matter of days, and can't be sure the problem would be solved (as maybe the problem comes because of the use of mootools), and as no error appears on the console it's almost impossible to find the real cause. Making some tests with the console it all seems to be a problem with the jQuery.bind() which is not binding the function for forms with conditionals.
After almost surrendering to the problem, and waiting to get an answer from other users in here, I tryed another possibility... Changing the page-template for the default additional option in Gantry4 (Contact Form) displayed the form without any problem! (with a contact form at the bottom of course). So I just made a copy of that page-template and just changed the title and deactivated the load of the `contactform` leaving the `mainbody` empty like this: echo $gantry->displayMainbody(); Don't know if it's the correct approach but that solved the issue.
stackexchange-wordpress
{ "answer_score": 0, "question_score": -1, "tags": "plugin gravity forms" }
How do i add comment fields in my page in WordPress How do i add comment fields in my page in WordPress My page design is shown below, Please help me to add comment field under the video during playing. ![enter image description here](
Check WordPress **Admin** and find **Settings** Menu. On clicking it you will find **Discussion** submenu. Check the Image below for reference :) ![enter image description here]( By adding custom css you can make it more beautiful
stackexchange-wordpress
{ "answer_score": 0, "question_score": 0, "tags": "comments" }
Dashboard links not working Since yesterday, all links on the Dashboard not working. If i click one link (left menu bar), always redirect the dashboard /wp-admin/ (homepage of dashboard). I have to open a page ten times to finally get to the page I would like to open. And it is, all links present. I have a manully installed the wordpress 4.7.2. - but nothing changed. Probably is this a plugin that can do (cache plugin)?
Those links are supposed to show submenus. If they are not showing up, that usually means your theme has a conflict with our plugin (90% of the time, this is boostrap). Please check our documentation about conflicts with Bootstrap as well as our FAQ entry about that.
stackexchange-wordpress
{ "answer_score": 2, "question_score": 3, "tags": "wp admin, dashboard" }
Woocommerce add custom button to backend order table I am currently working on a wordpress/woocommerce project. At the backend, when the user clicks on woocommerce/orders menu, it will display all available order details. In order this table, there are several fields/columns (such as order, ship to, date, total, actions). Under actions field, there are two buttons (order status and view). I want to add another button under this field. So, is there any code available that can be placed to functions.php to solve this problem. Thank you.
@mmm thanks for that code, I didnt know this filter yet. Do you know if it is also possible to add a tooltip that way? Anyway, I have a different solution to add a new button to this column, and also want to post it: add_action( 'woocommerce_admin_order_actions_end', 'add_content_to_wcactions_column' ); function add_content_to_wcactions_column() { // create some tooltip text to show on hover $tooltip = __('Some tooltip text here.', 'textdomain'); // create a button label $label = __('Label', 'textdomain'); echo '<a class="button tips custom-class" href="#" data-tip="'.$tooltip.'">'.$label.'</a>'; } Just replace the tooltip and label text and add your url in the link. * * * I tested the above code on an empty installation and this is what I get: ![enter image description here](
stackexchange-wordpress
{ "answer_score": 5, "question_score": 1, "tags": "plugin development, woocommerce offtopic" }
How to trigger click events using hooks I'm using Gravity Forms and after submission I want to use its built-in action `add_action( 'gform_after_submission', 'after_submission', 10, 2 );` to trigger a couple of click events from 2 different elements in that page. Is it possible? If so, how is it done?
It seems it's not really necessary to use php for this, but just `bind` will do the trick: $(document).bind('gform_confirmation_loaded', function($){ $("button").trigger("click"); }); And that's it! :)
stackexchange-wordpress
{ "answer_score": 0, "question_score": 0, "tags": "hooks, actions" }
Get posts from category from custom query Hello I have the following custom wordpress query. This displays all the blog posts just fine. <?php $mymain_query = new WP_Query( array( 'post_type' => 'post','posts_per_page' => '10' ) ); while($mymain_query->have_posts()) : $mymain_query->the_post(); ?> //shortened code below <div class="blog-post"> <h5><?php the_title(); ?></h5> <p><?php the_content(): ?></p> </div> <?php endwhile; ?> <?php wp_reset_postdata(); // reset the query ?> But I when I plug this into `archive.php` it is still calling all blog posts instead of the ones in that category. Can anyone suggest how to edit my code to only show the blog posts in that specific category? Thanks!
I figured it out. Here is my solution <?php $categories = get_the_category(); $category_id = $categories[0]->cat_ID; $mymain_query = new WP_Query( array( 'cat' => $category_id,'posts_per_page' => '10' ) ); while($mymain_query->have_posts()) : $mymain_query->the_post(); ?> //shortened code below <div class="blog-post"> <h5><?php the_title(); ?></h5> <p><?php the_content(): ?></p> </div> <?php endwhile; ?> <?php wp_reset_postdata(); // reset the query ?>
stackexchange-wordpress
{ "answer_score": 0, "question_score": 0, "tags": "posts, categories, archives, blog" }
How to change name "Profile" I want to change the name "Profile" to something else. ![enter image description here](
You could try the following. Add to your `functions.php` function admin_profile_menu() { remove_menu_page('profile.php'); add_menu_page( "NEWLABEL", "NEWLABEL", "", "profile.php", "", "dashicons-admin-users", "40" ); } add_action('admin_menu', 'admin_profile_menu');
stackexchange-wordpress
{ "answer_score": 0, "question_score": 0, "tags": "profiles" }
Automate dir and DB stack creation with WP-CLI This is how I create a database stack and a directory for WordPress in my Ubuntu environment: cat <<-DBSTACK | mysql -u root -p"${dbrootp}" CREATE USER "${domain}"@"localhost" IDENTIFIED BY "${dbuserp}"; CREATE DATABASE "${domain}"; GRANT ALL PRIVILEGES ON ${domain}.* TO "${domain}"@"localhost"; DBSTACK curl -L | tar -zx -C ${domain}/ cp ${domain}/wp-config-sample.php ${domain}/wp-config.php sed -ir "s/username_here|database_name_here/${domain}/g ; s/password_here/${dbuserp}/g" ${domain}"/ ${domain}/wp-config.php How would you reduce the amount of code with WP-CLI to get the same result?
WP-CLI has a bunch of helpful commands, including some to perform basic database operations. However, it's not its job to create new users in MySQL and grant them permissions on a newly created database. So that part of your script can't really be replaced with WP-CLI. You're still in luck though. The `wp core` command will help you download, install, update and manage a WordPress install. Plus `wp config` helps you manage the `wp-config.php` file. Instead of `curl -L | tar -zx -C ${domain}/` you can simply use `wp core download` to install the latest version of WordPress. To add the database credentials to the config file, you can use `wp config create --dname="${domain}" --dbuser="${domain}" --dbpass=${dbuserp}`. But we're not done yet! Why not fully install WordPress while we're at it? This can be done using `wp core install`: wp core install --url=example.com --title=Example --admin_user=supervisor --admin_password=strongpassword [email protected]
stackexchange-wordpress
{ "answer_score": 2, "question_score": 1, "tags": "database, installation, wp cli, automation" }
download button for audio file in post I am setting up a website for audio files, i have uploaded an audio file and inserted in a post in given link < the audio file inserted in this post is streamable but i also want to give a download button for the users so they can download the audio file. I inserted the button and then linked it with the audio file but when user hit the download the button the audio file starts to open instead of downloading. Is there something forcing the file not to download? i have seen the other website which is doing the same but there audio file is downloadable and mine is not here is the link <
Use this: <a href=" download="4%20Al-Rad%20Ayat-1%20Part-2.mp3">download</a> The structure is: <a href=" download="file.mp3">download</a> Here is a great article on the `download` attribute.
stackexchange-wordpress
{ "answer_score": 1, "question_score": 0, "tags": "plugins, posts, uploads, media library, audio" }
Do post_names have to be unique? I'm not 100% sure about this, so I'm asking: Does a post's post_name (aka: a post slug) have to be unique? Do they also have to be unique if each post has a different post type (a post and an attachment (like an image)?
Slugs need to be unique-ish. The function that determines what a slug will be is called, appropriately enough, `wp_unique_post_slug`. * Attachment slugs need to be unique across the whole set of slugs. Meaning that they cannot be shared with anybody, anywhere. * Page slugs (or any hierarchical post type) needs to be unique within that specific post type (and also not shared with any attachments). There's a few other restrictions, like you cannot use "embed" or "feed" or any other keywords WordPress already uses in URLs. So, you cannot have two pages named "about" for example, even if they are on different parts of the tree and thus have different parents. * Posts slugs must be unique across all posts (and also not shared with attachments). Same keyword restrictions.
stackexchange-wordpress
{ "answer_score": 4, "question_score": 1, "tags": "slug" }
Can't upload media to my Raspberry Pi Wordpress server Thanks in advance for any useful tips. I'll cut to the chase. I followed these guides to set up my wordpress server: 1 - < 2 - < _(referred the section titled "Set some permissions" only, otherwise all done with first tutorial)_ Uploading media still didn't work, so I performed the following in the `www` folder to try and cover all bases: `sudo chmod -R 777 .` Yet still, when I try to upload media in Wordpress, it says: _"filename.jpg HTTP error"_ What am I missing? About me: Not an expert in this stuff clearly, but can get the concepts pretty quickly with some explanation. Thank you!!
you need to change the owner of the wordpress folder to www-data. For example, if you put your wordpress folder in /var/www/my_new_wordpress_site, you will need to run the following command: `sudo chown -R www-data:www-data /var/www/my_new_wordpress_site`
stackexchange-wordpress
{ "answer_score": 1, "question_score": 2, "tags": "linux" }
How to remove comment spam in WordPress I'm new to WordPress. I have lot of issues through spam comments, it gets more time to check and delete those manually. I want to keep the comment fields. So is there any way to block/track spam comments in comment fields?
Just install a good anti-spam plugin. They will monitors site's comments for spam and automatically blocks spam comments. BTW WordPress come with Akismet which is a spam protection plugin installed by default. To enable the plugin, go to the Plugins and activate the Plugin. Akismet Anti-Spam
stackexchange-wordpress
{ "answer_score": 3, "question_score": 4, "tags": "comments, spam" }
Store Page Template Files in a Subfolder I have number of legal documents of different formats / layout that I need to display on a Wordpress site, however I don't want to have them as individual page-pagename.php files in the root of the project folder. I know I can use `get_template_part()` and load in different template files, but this won't really help me because the files are all of differing styles. Is there any way of storing pages in a subfolder called, say, legal, and then pulling in files from this folder as fully complete pages when people click on the appropriate links on the site, otherwise the root folder for the site is just going to be cluttered mess with endless individual page-pagename.php files. Many thanks
You can certainly use Page Templates for that. They're a specific type of template file that can be applied to a specific page or groups of pages. Plus, they can be stored in sub folders. All you need is to put something like this at the top of the template files: /** * Template Name: Legal Page */ After that, you can choose the "Legal Page" template when editing a page in the admin.
stackexchange-wordpress
{ "answer_score": 1, "question_score": 1, "tags": "page template, directory, template hierarchy" }
How to add new field to the account address? There's a need to add new field (e.g. vat-number) under the company name in the woocommerce plugin. What is the easiest / most reasonable way to achieve this? I wouldn't want to make copies from template files due to this small change nor install any plugin to avoid broken system (if the author prevents to update it at some point). I'll vote up all the answers that provide any useful information :-) Thanks!
The other guys assumed that you wanted to add your own store's VAT number, but I read it at you want the customer to add their VAT number when they create an account or order as guest. This is certainly possible, and WooCommerce does have a whole mechanism to hook into adding additional customer account fields. However, it's quite in-depth and not for the faint-hearted. I found this great tutorial that helped me get to grips with it. It's quite long, but it does take you through every place where the additional field(s) need to be registered. < Hope that helps
stackexchange-wordpress
{ "answer_score": 1, "question_score": 0, "tags": "custom field, woocommerce offtopic" }
Disable PAGESPEED SCRIPT INJECTION to IMAGE in theme files Since a few days I am bugged with INJECTION of PAGESPEED scripts for every image all across my theme files, and it just messes up the code (though it doesn't break the site). I want this to be removed somehow!!! I tried manual deletion but (it reappears on next load), and then I found it could be a prob of cloudflare that I use and disable all settings on cloudflare but still didn't work! Is there some way I can disable it? Somehow. ![Here is one instance where the code is messed up](
This might be caused by the mod_pagespeed Apache module. You should talk to your hoster to disable this.
stackexchange-wordpress
{ "answer_score": 2, "question_score": -1, "tags": "javascript, cache, bug" }
Site redirecting from http to https I just setup up a new WordPress site at < When navigating to the site I'm redirected from http to https. This throws a warning since I don't have a SSL certificate installed on this domain. How do I prevent WordPress from redirecting my site and resolving to http?
If your site and home URL are set to https, WordPress will redirect all requests made to it. Please check under Settings -> General if this is the case.
stackexchange-wordpress
{ "answer_score": 1, "question_score": 1, "tags": "redirect, https" }
Display post if a specific tag is present I want to display a particular message when a post has a specific tag on the article. I've done this, however the 'Hello' text is being shown no matter if the post has the tag 'test' or not. <?php if ( has_tag() == 'test' ) : ?> Hello <?php endif; ?>
According to the docs the input parameters can be: has_tag( string|int|array $tag = '', int|object $post = null ) so you could try e.g. if( has_tag( 'test' ) ) { ... } to check if the current post has the _test_ tag.
stackexchange-wordpress
{ "answer_score": 2, "question_score": 0, "tags": "tags, conditional content" }
How to get session token of current user in wp_login hook? I want to get current user's session token in the hook - wp_login. I have tried this code in functions.php: add_action('wp_login','test'); function test() { var_dump(wp_get_session_token()); //string(0) "" exit; } I am using wordpress 4.9.2
You can't access the `$_COOKIE` in this hook. You can only access `$_COOKIE` after the page HTTP headers are set with the `$_COOKIE` its mean in the next page. You have other hook that you can hook into to get the cookies in the function `wp_set_auth_cookie()` there is this action at the end. `do_action( 'set_logged_in_cookie', $logged_in_cookie, $expire, $expiration, $user_id, 'logged_in', $token );` So you can use it like this: add_action('set_logged_in_cookie', 'custom_get_logged_in_cookie', 10, 6); function custom_get_logged_in_cookie($logged_in_cookie, $expire, $expiration, $user_id, $logged_in_text, $token) { // do something... }
stackexchange-wordpress
{ "answer_score": 3, "question_score": 1, "tags": "hooks, login, cookies, session" }
Update slug (URL) of pending posts via phpMyAdmin I need to remove/delete slug of posts on pending via phpMyAdmin. Most of posts on pending have slug/URL which is different from their post title, deleting post slug/URL will force WP to generate new slug when post is published (which will be then as post title). Just for test, I tried manually to delete slug from some posts on pending via phpMyAdmin, and than to publish it via WP, and new slug is generated from post title. Now, I just need SQL function/query for that. So, I need to delete slug only from posts and only from posts on pending. I think it should be something like this: UPDATE wp_posts SET post_name = '' WHERE post_status = 'pending' AND post_type = 'post'; Could someone verify that please (or fix it if needed)?
One disadvantage of using that SQL query is that the slug will only be updated when you really go edit the post. Plus, it might cause odd behavior when any plugin tries to do something with an empty slug. A good alternative would be to use WP-CLI instead. First, you'll need a list of all pending posts: wp post list --post_type=post --post_status=pending --format=ids Next, you need a way to remove the slug of a post: wp post update <id> --post_name="" Now you can combine these commands like this: wp post update $(wp post list --post_type=post --post_status=pending --format=ids) --post_name="" This way, the post update will happen through WordPress' internal API instead of just SQL.
stackexchange-wordpress
{ "answer_score": 2, "question_score": 1, "tags": "query, mysql, phpmyadmin" }
Php echo into tag How can I add classes on the `echo` returns? <div class="author_sidebar"> <?php if ( is_singular( 'post' ) ) { echo get_avatar( get_the_author_meta( 'user_email' ), 75 ); echo get_the_author_meta( 'display_name' ); ?> </div> I managed to solve the problem by rapping the `echo` returns in `divs` this then allowed me to add `classes` into the `divs`
If you want to wrap an HTML tag around the user display names, you can simply close and open the PHP tags: <div class="author_sidebar"> <?php if ( is_singular( 'post' ) ) { ?> <div class="foo"><?php echo get_avatar( get_the_author_meta( 'user_email' ), 75 ); ?></div> <div class="bar"><?php echo get_the_author_meta( 'display_name' ); ?> <?php } ?> </div>
stackexchange-wordpress
{ "answer_score": 3, "question_score": -1, "tags": "php, tags, html" }
Wordpress permlink is not working Have a look, please: < and click on Blog. You should see my article, How to Use Tabs with Angular 5. Now click on this article to view it and you should get an "Oops! Can't find that." page. What's up with that? It looks like something odd is going on with single quotes in the link, but what's putting them there?
Have you tried to save the permalinks again? Step 1: In the main menu find "Settings > Permalinks". Step 2: Scroll down if needed and click "Save Changes". Step 3: Rewrite rules and permalinks are flushed.
stackexchange-wordpress
{ "answer_score": 2, "question_score": 0, "tags": "permalinks" }
PHP Date display as time ago Does anyone know how I can change this date format to time ago rather than DD/MM/YY <?php the_time('M j, Y') ?> Thanks.
There is a function for that: `human_time_diff()`. Use it like so: (`U` because we want the unix timestamp) <?php echo human_time_diff( get_the_time('U') ); ?> If you want additional text, you can use the following <?php printf (esc_html__('%s ago', 'yourlanguageslug'), human_time_diff(get_the_time('U'))); ?>
stackexchange-wordpress
{ "answer_score": 2, "question_score": 1, "tags": "php" }
Woocommerce Membership Expiry Date I'm hoping to be able to get the expiry date for the current user but can't seem to sort out how to do that. I've checked the documentation and see that there are some functions that allow for data to be pulled but none include the expiry date. The following gets basically everything but dates... wc_memberships_get_user_memberships() Any idea how I would go about doing this? Either I'm missing something obvious or it'll need to be done with a custom query.
According to the documentation, `wc_memberships_get_user_memberships()` returns a list of `WC_Memberships_User_Membership` objects. The `WC_Memberships_User_Membership` class has a `get_end_date()` method that will return the expiry date. So you should be able to do something like this: // Get memberships for the current user. $memberships = wc_memberships_get_user_memberships(); // Verify that they have some memberships. if ( $memberships ) { foreach( $memberships as $membership ) { // Print the expiration date in mysql format. echo $membership->get_end_date(); } } The mysql date format is the default, but you can also use something like `$membership->get_end_date( 'Y-m-d H:i:s' )` to have custom formatting or `$membership->get_end_date( 'timestamp' )` to get the timestamp.
stackexchange-wordpress
{ "answer_score": 4, "question_score": 2, "tags": "woocommerce offtopic" }
add filter login_redirect does not contain original requested redirect I link to WP's login page passing: redirect_to=play ...ttp://www.my.com/wp-login.php/? **redirect_to=play** ">Click here... I use the value (in this case: play) as a flag, not an actual redirect url, because I intercept the redirect request using: function my_login_redirect($redirect_to, $requested_redirect_to, $user) { var_dump($redirect_to); var_dump($requested_redirect_to); var_dump($user); } add_filter('login_redirect', 'my_login_redirect', 10, 3); Expected result: $requested_redirect_to would contain the value: play. However, wp login does not relay the original redirect_to value, in fact no mater what I do, the 2 params $requested_redirect_to and $redirect_to are always empty; only $user contains data. How do I pass my original redirect_to value all the way through the login process and into the filter: login_redirect?
You can use login_redirect filter. See here < I think this is what you are looking for. This will normally redirect all logins. To be able to redirect only when you want, you can use a query string parameter in the URL. Check for the parameter, if it exists redirect. Try to add this in your template functions.php file: add_action( 'login_form' , 'glue_login_redirect' ); function glue_login_redirect() { global $redirect_to; if (!isset($_GET['redirect_to'])) { $redirect_to = 'YOURURLHERE'; } else{ $redirect_to = $_GET['redirect_to']; } }
stackexchange-wordpress
{ "answer_score": 3, "question_score": 1, "tags": "filters, hooks, login, actions" }
increase nonce lifespan I want to increase the nonce lifespan from the default 12-24h, to 36-48h. I found the following code in the codex, but don't know where to put it. add_filter( 'nonce_life', function () { return 172800; } ); can i put this line in the functions.php to change the nonce lifespan sitewide? Is there an easy way to check the sitewide default lifespan of nonces? Are there any security issues with increasing the nonce lifetime by 24h?
1. Yes 2. Not really, but you can verify your change by login to admin and go to your profile. Wait 18 hours and try to submit. It should fail. 3. The longer the nonce expiration time is the longer an attacker might be able to trick you into performing unintended operation (but there is actually very slim chance for that unless you have an http site and like to use it in public wifi/networks, but then nonce is not your biggest problem).
stackexchange-wordpress
{ "answer_score": 3, "question_score": 2, "tags": "nonce" }
How to store wordpress title in a variable trying to run a PHP youtube v3 data in a WordPress theme $grab=ngegrab(' trying to store wp title in a variable so it won't echo the above API URL and it seems all method have tried isn't working **& q='.$unity.'** in the above code List I tired **$unity = $post->post_tite;** **the_title();** **get_the_title();** and even more is there still a way to make this work?
You're example is totally unclear. What is `ngegrab`, what is `$unity`, `$yesPage` and what do you mean with "WordPress title"? Short: what are you trying to do exactly? To get the title of a post, use `get_the_title()` as mentioned in the other answer. To get the document title (`<title></title>`), use `wp_get_document_title()`.
stackexchange-wordpress
{ "answer_score": 1, "question_score": -2, "tags": "loop, child theme, variables, get the title" }
Query to get the author who having maximum number of post (custom post type) I need to get the author information, who having maximum number of post(custom post type). Here is the code I tried to get the result. $author_query = new WP_User_Query(array ( 'orderby' => 'post_count', 'order' => 'DESC', )); $authors = $author_query->get_results(); foreach ( $authors as $author ) { echo $author->ID; echo $author->display_name; } The result is getting as post-count of normal posts. Here I have custom post type instead of default post. I need to get the result based on my custom post type's post count..
You can try with the following query, where the author data as well as the post count can be retrieved. $sql = "SELECT SQL_CALC_FOUND_ROWS wp_users.ID,post_count FROM wp_users RIGHT JOIN (SELECT post_author, COUNT(*) as post_count FROM wp_posts WHERE ( ( post_type = 'custom-post-type' AND ( post_status = 'publish' ) ) ) GROUP BY post_author) p ON (wp_users.ID = p.post_author) WHERE 1=1 ORDER BY post_count DESC"; $result = $wpdb->get_results($sql,OBJECT); print_r($result);
stackexchange-wordpress
{ "answer_score": 2, "question_score": 2, "tags": "custom post types, wp query, sql" }
Adding string before php I need to add a string in front of the following php code, what Is the best method of doing this? <?php echo human_time_diff( get_the_time('U') ) . __(' ago', 'yourlanguageslug'); ?><br/>
`<?php echo "Posted: ".human_time_diff( get_the_time('U') ) . __(' ago', 'yourlanguageslug'); ?><br/>` It's not that hard. but, you should these small things.
stackexchange-wordpress
{ "answer_score": 1, "question_score": 0, "tags": "php" }
How to disable XML-RPC from Linux command-line in a total way? I read near the end of this guide regarding utilizing SSHguard to protect WordPress from Brute force attacks that after configuring SSHguard the relevant way, one must: > disable XML-RPC by blocking all remote access to /xmlrpc.php in your web server configuration. * I don't use XML-RPC in any of my websites. * I use Nginx as my web server. I'm not sure what is the best way to totally block XML-RPC. Nginx conf for each site? WP-CLI operation per site? What is the common way to do so?
On nginx, to block access to the xmlrpc.php file, add this location block to the server block of your configuration file: location ~ ^/(xmlrpc\.php) { deny all; }
stackexchange-wordpress
{ "answer_score": 4, "question_score": 2, "tags": "security, wp cli, xml rpc, command line, ssh" }