INSTRUCTION
stringlengths
11
999
RESPONSE
stringlengths
0
999
SOURCE
stringlengths
16
38
METADATA
dict
categories should be available across all custom post types ![enter image description here]( Two different post types have different category types. Is it possible if two different posts types have same category types? Further Explanation: A particular category should be available across every post type, and there shouldbe no need to create it again individually for every post-type.
What you want is the normal behaviour if you register a taxonomy to multiple post types. What you appear to have done here is register a _new_ Category taxonomy for your Celebrity post type. To add the default Category taxonomy to a post type use `register_taxonomy_for_object_type()`. register_taxonomy_for_object_type( 'category', 'celebrity' );
stackexchange-wordpress
{ "answer_score": 3, "question_score": 0, "tags": "custom post types, php, functions" }
Fastest way to install a multisite? I setted up a Ubuntu-Nginx VPS machine with phpmyadmin and WP-CLI. I'm ready to start working with WordPress. What's the fastest way to install a multisite? Maybe with WP-CLI, maybe there's a ready, remote, communal script I could run with `curl`? Thanks,
The fastest way will be wp cli usage. Look a few links. This might help you. multisite convert multisite install small tutorial
stackexchange-wordpress
{ "answer_score": 0, "question_score": 0, "tags": "installation, linux" }
Accessing plugin settings in gutenberg I'm trying to build a gutenberg block (via plugin) that interfaces with a third-party api via credentials. I'm unsure how to, or even if I can, access a plugin's settings in gutenberg in order to grab a potential credentials field for use in the block. (I understand there's potential to put something in the editor's sidebar, but I need a persistent global setting that doesn't have to be set with every block.) Am I missing something in the documentation or is this not possible yet?
The WordPress way to access PHP variables with JavaScript is to use `wp_localize_script()`. function wpse_enqueue_scripts(){ wp_enqueue_script( 'wpse', PATH_TO . 'script.js' ); wp_localize_script( 'wpse', 'credentials', $credentials ); } add_action( 'wp_enqueue_scripts', 'wpse_enqueue_scripts' ); Then in your JavaScript, you can access the credentials like console.log( credentials );
stackexchange-wordpress
{ "answer_score": 7, "question_score": 8, "tags": "plugin development, settings api" }
Email reply to multiple email addresses not working I want that email reply should be received at multiple email address. But it is not working for me. I have tried different ways but none of these working for me. I am trying this header but it is only replying to the last email address. $to = "[email protected]"; $subject = "my email subject"; $message = "my email message"; $headers = array(); $headers []= "MIME-Version: 1.0\r\n"; $headers []= "Content-Type: text/html; charset=UTF-8\r\n"; $headers []= "Reply-To: <" . $EmailAddress1 . "> <" . $EmailAddressss2 . ">" . "\r\n" ; wp_mail($to, $subject, $message, $headers); I have tried without braces as well but this one is also not working $headers []= "Reply-To: [email protected],[email protected]\r\n"; I do not have much idea about this so little guidance about this will be much appreciated. Thank you!
**Unfortunately this is not widely supported** , not because WordPress does not support it, but because most email clients do not support it, so it cannot be relied upon. Instead, consider using a mailing list and use the mailing lists address as the reply to field
stackexchange-wordpress
{ "answer_score": 6, "question_score": 3, "tags": "wp mail" }
wp remote post getting a 404 error code $info = array( 'values' => array( 'email' => '[email protected]', 'firstname' => "firstname", 'lastname' => "lastname", 'source' => "WEB", ), ); $infoo=json_encode($info); $sf_auth = 'Bearer ' . $data['accessToken']; $finalUrl=" $result= wp_remote_post( $finalUrl, array( 'method' => 'POST', 'timeout' => 45, 'redirection' => 5, 'httpversion' => '1.0', 'blocking' => true, 'headers' => array( 'Content-Type' => 'application/json', 'Authorization' => $sf_auth, ), 'body' => $infoo, 'cookies' => array() ) ); Trying to post it within wp but i am receiving message: Not Found and errorcode: 404 CAn anyone what i am doing wrong??
I solved it by changing the method to PUT & httpversion to 1.1
stackexchange-wordpress
{ "answer_score": 1, "question_score": 1, "tags": "http api" }
Why is wp_localize_script returning false? I am enqueuing the script.js via a plugin succesfully but the wp_localize_script is not working and returning false. I have no clue why... object_name is unavailable in the script.js when I remove the var_dump function my_enqueue() { wp_enqueue_script( 'ajax-script', plugins_url( '/script.js', __FILE__ ), array('jquery') ); var_dump(wp_localize_script( 'ajax_script', 'object_name', array( 'foo' => 'bar' ) )); } add_action( 'wp_enqueue_scripts', 'my_enqueue' );
Handle name doesn't match registered script name in your snippet. `wp_enqueue_script` has `ajax-script` and localize has `ajax_script` notice the dash and underscore. You should also follow example from the docs a. register, b. localise, c. enqueue; like so: <?php // Register the script wp_register_script( 'some_handle', 'path/to/myscript.js' ); // Localize the script with new data $translation_array = array( 'some_string' => __( 'Some string to translate', 'plugin-domain' ), 'a_value' => '10' ); wp_localize_script( 'some_handle', 'object_name', $translation_array ); // Enqueued script with localized data. wp_enqueue_script( 'some_handle' );
stackexchange-wordpress
{ "answer_score": 4, "question_score": 0, "tags": "ajax, javascript, wp localize script" }
Difference between "comment_form_default_fields" AND "comment_form_fields" What is the difference between `comment_form_default_fields` and `comment_form_fields`? Description in the official code reference seems to differ only by the word "default". What's the difference in application? Which hook can I use to change the html output of fields for example? And what's the purpose of the other hook then?
Using `comment_form_default_fields` filter hook you can change _email_ , _author_ and _url_ fields but cannot change _comment_ field. And using `comment_form_fields` filter hook you can change all the 4 fields. You can use both filter hooks to change html.
stackexchange-wordpress
{ "answer_score": 1, "question_score": 0, "tags": "theme development, comments, hooks" }
Do translation functions like __e() have to take strings in English in themes? I'm developing a theme and curious if strings could be written in a language different from English and still be properly translatable? What I mean is when using translation functions in a custom theme, e.g. `__('string','textdomain')` or `__e('string','textdomain')` can I use language different from English to write the string, for example: `__e('строчка','textdomain')`? Or do I have to write everything in English and then provide a translation files for other languages (presumably because theme's default language defaults to the WPLANG setting in wp-config.php)? Hope someone can clarify this.
Yes, you can use any language you want. But if you want your theme to be translated by everyone, you should pick a language that people are likely to know, like English. If you, for example, care only about former USSR countries, Russian might be as good.
stackexchange-wordpress
{ "answer_score": 1, "question_score": 0, "tags": "theme development, translation, language" }
Create human verification for wordpress contact form with two random number I have two number and an operator in three variables. For example $number1, $number2 and $operator. $operator contains only an operator from an array of (+, -, *, /). Now my question is how can I calculate mathematical operation with these three variables? For example $number1 ($operator) $number2 = ?
Recommend you just stick to `*` and `+`, not expect people to deal with decimals and negative numbers. It is best to keep it simple as possible and not attempt to `eval` the string as an expression which is not good practice: $operators = array('+', '*'); $operator = rand(0, 1); $display = $number1.' '.$operators[$operator].' '.$number2; if ($operators[$operator] == "*") {$result = $number1 * $number2;} elseif ($operators[$operator] == "+") {$result = $number1 + $number2;} Of course there are other ways to calculate without `eval`, such as in this answer, but probably not worth it unless you are doing something more complex.
stackexchange-wordpress
{ "answer_score": 0, "question_score": -1, "tags": "captcha" }
Will I have problem with PHP 5.5 and WordPress 4.9.4? I made a fresh installation of the newest version of the WordPress in `Ubuntu Server 14.04` where the PHP version is `PHP 5.5.9-1ubuntu4.22 (cli) (built: Aug 4 2017 19:40:28)` I managed to install the WordPress site and a purchased theme successfully till now. Will I encounter any problem with the site development? I am asking because later I noticed this in WordPress requirements.. > PHP version 7.2 or greater
No, you will not face any problem because of `PHP 5.5`. _WordPress recommends (not required or mandatory)`PHP 7.2` because it has better performance than the older versions._ If you need better performance than `PHP 5.5` then you should definitely use `PHP 7.2`. Btw, WordPress even smoothly works with `PHP 5.2.4`!.
stackexchange-wordpress
{ "answer_score": 1, "question_score": 0, "tags": "php, compatibility" }
Get page id of current page from template I am trying to get page id from my `template-contact.php` like this : global $post; echo $post->ID; It's showing 85 but page id is 96, I want to get id because I want to fetch meta of current page. Here is my template code. <?php /* Template Name: Contact Page */ ?> <?php get_header() ?> <?php global $post; echo get_post_meta($post->ID, 'contact_page', true); ?> <?php get_footer() ?> Please help
To get the ID of the page being queried from outside the loop or before the global post object has been set, use `get_queried_object_id()`. <?php /** * Template Name: Contact Page */ get_header(); ?> <?php $page_id = get_queried_object_id(); echo get_post_meta( $page_id, 'contact_page', true); ?> <?php get_footer() ?>
stackexchange-wordpress
{ "answer_score": 5, "question_score": 1, "tags": "page template" }
wp_dropdown_pages : choose post status to list in dropdown I would like to create a dropdown of all _schedule_ and _publish_ CPT posts. I seems function wp_dropdown_pages only displays list of _publish_ posts, is it possible to choose which post states to display ? Thanks
If you look at the source for the function, you can see that the arguments to the function are passed directly through to `get_pages()`. That function supports a `post_status` argument that can be an array of statuses. So to do what you want all you need to do is pass the post statuses you want into a `post_status` argument of `wp_dropdown_pages()`: wp_dropdown_pages( arrray( 'post_status' => array( 'future', 'publish' ), ) );
stackexchange-wordpress
{ "answer_score": 1, "question_score": 0, "tags": "dropdown, post status" }
ACF Date fileds to Age Convert I'm trying to display Differnet Age from Advanced Custom Field. But, it's displaying total age by splitting Days, years, months etc. Actually, I want to Calculate Separately. Example: I want to display as- > 28 years | 343 months | 10444 Total days | 250,632 hours | 15,037,920 minutes | 15,037,920 seconds I tried using this code, but not working. <?php $date = get_field('dob'); $birthday = new DateTime($date); $interval = $birthday->diff(new DateTime); echo $interval->days.'Total days'."\n"; echo $interval->y.' years'."\n"; echo $interval->m.' months'."\n"; echo $interval->d.' days'."\n"; echo $interval->h.' hours'."\n"; echo $interval->i.' minutes'."\n"; echo $interval->s.' seconds'."\n"; ?> It's displaying- > 10444 Total days 28 years 7 months 2 days 0 hours 4 minutes 32 seconds
$birthday_ts = strtotime( get_field('dob') ); $now = current_time( 'timestamp' ); $years = intval( ( $now - $birthday_ts ) / YEAR_IN_SECONDS ); $months = intval( ( $now - $birthday_ts ) / MONTH_IN_SECONDS ); $weeks = intval( ( $now - $birthday_ts ) / WEEK_IN_SECONDS ); $days = intval( ( $now - $birthday_ts ) / DAY_IN_SECONDS ); $hours = intval( ( $now - $birthday_ts ) / HOUR_IN_SECONDS ); $minutes = intval( ( $now - $birthday_ts ) / MINUTE_IN_SECONDS ); $seconds = intval( ( $now - $birthday_ts ) ); echo $years . ' years | ' . $months . ' months | ' . $weeks . ' weeks | ' . $days . ' days | ' . $hours . ' hours | ' . $minutes . ' minutes | ' . $seconds . ' seconds' ; I just tried it with my own birth date, 16-08-1978 and got this result: 39 years | 481 months | 2061 weeks | 14433 days | 346394 hours | 20783654 minutes | 1247019262 seconds
stackexchange-wordpress
{ "answer_score": 1, "question_score": -1, "tags": "php, functions, custom field, advanced custom fields" }
Text not wrapping properly around image in Wordpress Visual Editor This question pertains specifically to the Wordpress Visual Editor _ I have searched for an answer to this question because it must be a common issue_ but sadly not been able to find a solution anywhere_ including Stack Exchange The problem is getting text to wrap all the way up the side of an image _ I just cannot get it to do it as I would expect it to in webpages that are NOT Wordpress specific _ The display in the visual editor shows the image and text exactly how I want it ![enter image description here]( But the text and the image on the actual page looks like this ![enter image description here]( The Wordpress Text Editor code is this <p style="text-align: left;"><img class="alignleft size-medium wp-image-301" src=" alt="" width="300" height="159" /> Text content </p> If anyone could advise on how to resolve this issue I would be very grateful _ Thanks in advance : )
take advantage of these new CSS classes for image alignment img.alignright { float: right; margin: 0 0 1em 1em; } img.alignleft { float: left; margin: 0 1em 1em 0; } img.aligncenter { display: block; margin-left: auto; margin-right: auto; } .alignright { float: right; } .alignleft { float: left; } .aligncenter { display: block; margin-left: auto; margin-right: auto; } find here: Text Wrapping Issue
stackexchange-wordpress
{ "answer_score": 0, "question_score": 0, "tags": "images" }
Pagination on a custom post type loop I've read a lot of questions about this topic. None of them solve my issue. **Poblem** : pagination is shown at page 1 but page 2 returns 404. The query and loop are in front-page.php: // WP_Query arguments $args = array( 'post_type' => 'trabajo', 'posts_per_page' => '2', 'paged' => ( get_query_var('paged') ) ? get_query_var('paged') : 1, ); // The Query $trabajo_query = new WP_Query( $args ); $temp_query = $wp_query; $wp_query = NULL; $wp_query = $trabajo_query; // The Loop if ( have_posts() ) { while ( have_posts() ) { the_post(); the_title(); } } wp_reset_postdata(); the_posts_navigation(); $wp_query = NULL; $wp_query = $temp_query; // Reset
I found the final answer here: < Page 2 of front page was taking pagination from main query, not from my custom query. I've taked these actions: **1\. To change name of front-page.php to index.php** in order to get the main query every time page is loaded (even when paginated) **2\. To change main query with pre_get_posts** in order to show posts of my CPT: add_action( 'pre_get_posts', function ( $q ) { if ( $q->is_home() && $q->is_main_query() ) { $q->set( 'posts_per_page', 1 ); $q->set( 'post_type', 'trabajo'); } }); **3\. Do a normal loop in the index.php:** if ( have_posts() ) { while ( have_posts() ) { the_post(); the_title(); } } wp_reset_postdata(); the_posts_navigation(); Works perfectly!
stackexchange-wordpress
{ "answer_score": 2, "question_score": 1, "tags": "custom post types, wp query, pagination" }
Is it possible to issue a theme update that requires a new plugin? I developed a forked version of the Understrap theme for a project I completed. The theme has since been used in about 300 sites. Recently we found a bug relating to a plugin used that the developer has been unable to resolve after more than a year of requests. The solution is to uninstall that plugin and install an alternate plugin. My question relates to the theme update mechanism, I used this library but I'm not sure if it is possible to deactivate the existing buggy plugin and install the alternate plugin via the update? Using the update would obviously make it easier to roll out the change
You should never deactivate or uninstall or even install any thing which is not part of your theme without explicit user consent. If a theme can not work without a plugin, its functionality should be shipped as part of the theme, or it just have to live with whatever bug that plugin has. The best you can probably do is to have an admin notice about the incompatibility.
stackexchange-wordpress
{ "answer_score": 0, "question_score": 0, "tags": "theme development, automatic updates" }
Correctly enqueue scripts of type=text/paperscript (PaperJs Library) I need to use Paper.js (< and specifically one of their examples (< on a WordPress website. Usually, scripts are enqued to WP with a PHP function that adds scripts of type text/javascript (< and should be fine for the Paper.js library itself. But... The script utilizing Paper.js should be of type text/paperscript (< and the only solution I could come up with is echo both script tags to my (child theme to a Genesis Framework) header.php file: <script src=" integrity="sha256-qZnxjtwxg51juOcYyANvBWwFoahMFNB2GSkGI5LGmW0=" crossorigin="anonymous"></script> <script type='text/paperscript' canvas='smoothCanvas' href='../js/smoothing.js'></script> Is there any other solution? I tried to search some tutorials for Paper.js on Wordpress, but couldn't find anything.
I'm not sure if this will solve your problem, but you can use the `script_loader_tag` filter to change the type `text/javascript` to `text/paperscript` add_filter( 'script_loader_tag', function( $tag, $handle, $src ) { if( 'your-script-handle' === $handle ) { $tag = str_replace( 'text/javascript', 'text/paperscript ', $tag ); } return $tag; }, 10, 3 );
stackexchange-wordpress
{ "answer_score": 2, "question_score": 0, "tags": "javascript, wp enqueue script, library" }
Detect When User Reads Full Article? I've been trying to find a way to detect when a user reads the full article on my blog so I can compare impressions verses actual reads (a bit like Medium does). Does anyone know of a plugin that does this (I've searched and cannot find any), or a way to detect this using Google Analytics as an event or something? Thanks for your help!
Haven't seen a plugin that does this, since each theme would differ. But for a custom solution that would work with Google Analytics events see #9 here: < OP also found this more specific article: < (These are in comments above, just posted to make it faster for those looking for something similar to find an accepted answer.)
stackexchange-wordpress
{ "answer_score": 1, "question_score": 1, "tags": "javascript, google analytics, statistics" }
"wp_enqueue_style();" don't load new edited style First, sorry my english. I am using Local by flywheel to manager my site files and my wordpress version is 4.9.4. Here is the problem, When I use wp_enqueue_style('wharever', get_stylesheet_uri()); To load style.css at the first time with a just simple content inside: body { color: orange; } Everything is just fine, and we have a page with everything in orange text, but when I change the style.css body color to green (or whatever), they just don't change, and always are orange. PS.: in wp_enqueue_style, I changed the version parameter and he changes, but only at the first time and stuck with the first color I put for the version that was put. If this is a feature of wordpress, how can I turn this off? This don't see quite useful know that we can't change style.css at will just to test without change version.
Another solution is to use `filemtime` for the cachebusting, so that the last modified timestamp is used as the querystring variable. This has the advantage that of still using the browser cache, and yet, a new file is served when the file is actually changed because the querystring changes. eg. $lastmodtime= filemtime(get_stylesheet_directory().'/style.css'); wp_enqueue_style('whatever', get_stylesheet_uri(), array(), $lastmodtime);
stackexchange-wordpress
{ "answer_score": 3, "question_score": 2, "tags": "php, css, wp enqueue style" }
Alignment Problem I have an alignment problem with datetime of the comment "not post". The main problem is that I'm on RTL mode and the theme doesn't fully support such environment. So basically, the datetime of the comment inside the post page is placed on the user's avatar. I couldn't find that specific datetime. I searched everywhere. Can anyone please help me to fix this? My site Please see the screenshots. The theme I'm using is called Steed and I can't find a fix for that problem. ![This is how it should look like.]( ![This is what I got.]( Thank you, Badee
The avatar image is overlapped because of the negative margins in this CSS: .comment-author.vcard img { margin-bottom: -18px; } div.comment-metadata { margin: -5px 0 0 8.3%; }
stackexchange-wordpress
{ "answer_score": 1, "question_score": 0, "tags": "theme development, themes, child theme, theme customizer, theme options" }
Wordpress Site says Front Page is 404 When Not Login I have a Wordpress site, I have the Front Page settings right in the Reading settings, but when I goto my Wordpress site and I am not login, I get a 404 error and my page looks messed up. When I am login to Wordpress my Front Page looks like it should and I dont get a 404 page. Here is my site, why is this happening? makinghermrs.com Here is my .htaccess file: # BEGIN WordPress <IfModule mod_rewrite.c> RewriteEngine On RewriteBase / RewriteRule ^index\.php$ - [L] RewriteCond %{REQUEST_FILENAME} !-f RewriteCond %{REQUEST_FILENAME} !-d RewriteRule . /index.php [L] </IfModule> # END WordPress Also I am unable to change the static front page in my settings, when I save it, nothing gets changed. More information in another question I asked: Issue with my theme
I was able to solve this problem, I found this code in my theme functions.php file: function switch_homepage() { if ( is_user_logged_in() ) { $page = 738; // for logged in users update_option( 'page_on_front', $page ); update_option( 'show_on_front', 'page' ); } else { $page = 738; // for logged out users update_option( 'page_on_front', $page ); update_option( 'show_on_front', 'page' ); } } add_action( 'init', 'switch_homepage' ); So I remove it and now everything is working
stackexchange-wordpress
{ "answer_score": 0, "question_score": -4, "tags": "404 error, frontpage" }
I want to remove "continue reading..." in rss feed I want to remove "continue reading..." in rss feed. Which php file should I change and which code should I edit?
Add code on your functions.php at last. After update check feed url remove browser cache. function custom_auto_excerpt_more( $more ) { return '...'; } add_filter( 'excerpt_more', 'custom_auto_excerpt_more' ); ![enter image description here](
stackexchange-wordpress
{ "answer_score": 1, "question_score": 0, "tags": "rss" }
Distribute Custom Post in different pages I have a custom post type and a page where those are shown. I have been asked to make different pages and distribute those already created custom post types but I'm scratching my head a bit about how to achieve that. The "easy way" would be to create 6 different custom post types, 1 for each new page and re-create the posts which would be a pain. Is there a way to use the already created custom post types and assign them to different pages? Maybe with a category or a custom field?
Assign each one a category or a tag (or, even better, a custom taxonomy) and then for each page create a page template and do a custom query that loads only those posts with that particular tax. Hope that helps
stackexchange-wordpress
{ "answer_score": 1, "question_score": 0, "tags": "custom post types, advanced custom fields" }
Most performant/functional way to add actions/filters? This question may seem trivial however as I see all of those styles very often I wonder if there is a difference (e.g. in performance or functionality): Possibility 1: function myabc() { } add_action('init','myabc'); Possibility 2: add_action('init','myabc'); function myabc() { } Possibility 3: add_action('init',function(){ }); Can you give a short explanation if any style may have an advantage about the other? Or are they overall equal?
There is no difference between 1 and 2. Both are same in every single case. So, I'll consider 1 and 2 as **A** and 3 as **B**. Now in **A** the `add_action()` callback function is a named function whereas in **B** the callback function is an anonymous function and this is the main difference. I hope you know that using `remove_action()` we can deregister an action hook and to do that we have to pass two parameters. One parameter is the hook name and another is the callback function name. So if you register a hook with an anonymous callback function it's not possible to deregister that later! Hope it's clear now.
stackexchange-wordpress
{ "answer_score": 1, "question_score": 0, "tags": "filters, actions, performance" }
exclude a category from a search on a specific page I have a search bar on 2 pages in my site and on my page called archive I want to exclude a category called economics (id - 9) from the search. I have placed this in my functions.php file: function archive_search_filter( $query ) { if ( $query->is_search && $query->is_main_query() ) { $query->set( 'category__not_in' , '9' ); } } add_filter( 'pre_get_posts', 'archive_search_filter' ); and it works perfectly but I want to only have this implemented on the page called archive. If I try an if statement with is_page('archive') along with this it is not working and I'm not sure of a solution. I'm wondering if the functions.php loads before it can tell what page it is and if there is another way to get this to work.
The problem is that `pre_get_posts` is called _after_ you leave the page, so you must also test to see if the search was done from there and for that you can use `wp_get_referer()` So _(in theory, sorry I haven't the time to test this)_ you could have `if ( !is_admin() && $query->is_search() && $query->is_main_query() && wp_get_referer() == " ) {` Hope that helps _PS: Always add a`!is_admin()` check to make double-sure you're not effecting admin queries... belt & braces!_
stackexchange-wordpress
{ "answer_score": 1, "question_score": 1, "tags": "functions, categories, query" }
What is the best way to install a WordPress starter theme into a Docker environment? I'm recently learning more about starter theme development and would love to get some feedback or tips from any pros here on the forum that have experience in setting up a docker environment for a WordPress starter theme. To be specific, how do we get an underscores.me theme up and running in Docker? I'm all ears
It's easy to install a theme on WordPress. There are a couple of options, but for the underscores.me starter theme, the easiest option would be to go to < and enter your theme's name and then click the "Generate" button. Wait a moment, and a zip file should start downloading. Once you've got the zip file, head over to your WordPress admin and navigate to Appearance -> Themes. On the themes page, click the "Add New" button and then "Upload Theme" and then follow the prompts to install and activate it. Have fun!
stackexchange-wordpress
{ "answer_score": 2, "question_score": 1, "tags": "docker" }
How do I add a custom css to all posts without affecting homepage css? As the title says, How can I add a custom CSS to all posts without affecting homepage CSS on WordPress? And I know that some plugins like "WP Add Custom CSS" would work for this and I am actually using it, and it does work but, what I want to do is give all my posts the same exact code, I don't want to give every post manually the same code over and over. Because if I wanted to change this code later on, then I will have to go back and edit every post that I made with this new code change. For example, I have this CSS code: .post-meta { margin-right: 0px !important; } Every post needs to have this code but without affecting homepage CSS.
By default, WordPress sets various classes to `<body>` depending on which page, template, parent, .. you are on. For a single post, some of these are `single` and `single-post`, so you could use the following body.single.single-post .post-meta { margin-right: 0px !important; }
stackexchange-wordpress
{ "answer_score": 5, "question_score": 0, "tags": "php, customization, css, html" }
Do I need to escape get_the_post_thumbnail function? I am developing a WordPress theme for WordPress.org. Do I need to escape `get_the_post_thumbnail` function? I want to use it outside the loop. So, I won't be able to use `the_post_thumbnail`. Please let me know if I need to escape `get_the_post_thumbnail` and if yes, how do I do it? Thanks in advance.
No, you don't have to escape the data. And it doesn't need to be escaped. Please take a look at `the_post_thumbnail()` function, it didn't do any escaping. So no worries.
stackexchange-wordpress
{ "answer_score": 1, "question_score": 0, "tags": "theme development, security" }
What is the proper way to include a PHP framework into my theme? I am using a Twitter Timeline PHP framework to display a list of tweets with favorite/retweet interactions. I have it all configured and working as a standalone solution currently and I am wondering what the best way to incorporate it into my custom Wordpress theme would be. Is it as simple as creating an `inc` folder, placing all the files in there and then adding `<?php include_once('inc/twitter.php'); ?>` into my template file where I want the tweets to display? Or is there a better practice?
It is that simple. Code away! if it's in a plugin I do this: $plugin_url = plugin_dir_url( __FILE__ ); include_once($plugin_url . 'inc/twitter.php'); if it's in a theme file include_once(get_stylesheet_directory_uri().'inc/twitter.php');
stackexchange-wordpress
{ "answer_score": 2, "question_score": 0, "tags": "php, include" }
Wordpress automatically adds links to uploaded images Wordpress automatically adds the link to every image I upload within Media. And then I can’t find a way to remove it. How can I upload images without links or just remove it? There is just no option to choose whether to upload with link or without. I tried many plugins for that but none seems to be working. This happens when I use uploaded images in default Gallery widget by Wordpress. I also tried this code, but nothing. Code: add_filter( 'the_content', 'attachment_image_link_remove_filter' ); function attachment_image_link_remove_filter( $content ) { $content = preg_replace( array('{<a(.*?)(wp-att|wp-content\/uploads)[^>]*><img}', '{ wp-image-[0-9]*" /></a>}'), array('<img','" />'), $content ); return $content; }
You adjust that when you insert the image into the post, not when you upload it. When you upload the image, you will be looking at it on the Media Library page. On the right hand side is a column that says "ATTACHMENT DETAILS". Scroll down on that, and look for "ATTACHMENT DISPLAY SETTINGS". The field you're looking for is called "Link To" and you want to set it to be "None" before you click the "Insert into Post" button. ![enter image description here](
stackexchange-wordpress
{ "answer_score": 4, "question_score": 0, "tags": "php, images, uploads, media, gallery" }
Is it possible to increase php memory without directives in wp-config.php, .htaccess or php.ini? I using a plugin that crashes due to lack of memory. But I'm on a host (Pantheon) that uses git for file updates between a Dev server (where I have FTP access) and a Live server (where I have no FTP or SSH access). I can't change wp-config.php and commit the file because the database details are different between Dev and Live. php.ini files are not allowed, and PHP directives in .htaccess are not allowed. How can I increase PHP memory for Live? Can I add a directive in a theme file? Like functions.php? Will that work for plugin memory?
Using `ini_set("memory_limit", "256M");` in a simple plugin works for the most part. Ugly, yes; but it appears to work in my case.
stackexchange-wordpress
{ "answer_score": 0, "question_score": 1, "tags": "php, wp config, memory" }
How to insert Collate into Wordpress search query? I want to improve my default Wordpress search query and add `COLLATE utf8_bin`. What is the best way to do this action? Should I edit _wp-includes/query.php_ or manipulate with _functions.php_ file from **themes** folder?
You should add the following code to the `functions.php` of your theme (and it is better to make all modifications in child theme): add_filter( 'posts_search' , 'posts_search' ); function posts_search( $search ) { $search = str_replace( 'LIKE', 'COLLATE utf8_bin LIKE', $search ); return $search; } It works. You can check it on my test site: returns one post, but returns nothing.
stackexchange-wordpress
{ "answer_score": 1, "question_score": 0, "tags": "query, search" }
Wordpress.com how are 'related posts' determined? Wordpress.com allows inclusion of 'related posts' below each post. How does it choose which posts to display - by matching category, tag, or both?
I believe that related posts have similar tags, at least according to this article, which includes code for a query that will include related posts: < Couldn't find anything about related posts in a quick look in the Codex.
stackexchange-wordpress
{ "answer_score": 1, "question_score": -1, "tags": "wordpress.com hosting" }
block countries from shipping to them in WooCommerce I need to block certain countries in woocommerce that we don't ship to. For example, we don't ship to China, so I want to make sure that on checkout, when the select china as their country it won't allow them to continue to payment unless they select another country we do ship to. I feel like this option is somewhere in Woocommerce under shipping but I really can't find it. Thank you to everyone for your help.
you can simply go to the woocommerce setting and then find the Selling location(s) in General setting and select sell to all countries except for... ![enter image description here](
stackexchange-wordpress
{ "answer_score": 6, "question_score": 1, "tags": "plugins, woocommerce offtopic" }
customize search result in wordpress i'm creating a Reference website, in this website there are many texts about some knowledge, The main task of this site is to find the keywords (or words close to them) in the content ,And search results are based on words, not the whole text. some lines before and after the keyword, and if the user wants to see the full text enter to it , and if the keyword has been used more, the results will be displayed it individually.My problem is that I do not know much coding, and all the plugins only show the whole text from the beginning in the results. I'm currently using the search&filter plugin. this site has done what i want This site they show the keyword after each result and you can see every keyword in a content,and after the keyword you can see the words that close to the keyword
What shows in search results is not always controlled by search plugins. You probably need to adjust your theme. Create a child theme, copy `search.php` from the parent theme into the child theme, and wherever it calls for `the_content()` replace that with `the_excerpt()`. Some search plugins may modify this behavior, so you'll have to do some trial and error, but you can start with out-of-the-box WP search to test and then try a variety of plugins. If you have budget available, there are several paid search options that allow you to adjust relevancy and weighting of different items like the title, content, etc. Elastic, Swiftype, and others give you a lot more control over your search results without having to have coding knowledge or even adjust your theme - you pick what shows in the serps right in their UI.
stackexchange-wordpress
{ "answer_score": 0, "question_score": 0, "tags": "search" }
SMTP not working for Comments Email Notifications The problem is that I'm not receiving wordpress emails except the ones generated by sucuri plugin. I want admin to receive email notification on every new comment and post updates. Previously, my testing site was placed on bytehost.com where the default wordpress mailer worked just fine, used to send sucuri plugin emails and comments notification emails. Now as our official site host does not allow to use PHPmailer, so the default setting wont work. I have install Email SMTP for configuration, and it kinda worked only for sucuri plugin emails but not for comments. Please help me with the configuration settings. I have already updated host and port of our server in SMTP plugin. Also as the server is our own, so there is no Cpanel. All I have got is host and port. I'm seeking guidance with class-phpmailer.php is it needs to be configured If you want any file to be pasted, please ask and help me with this issue.
I added host settings in class-phpmailer file i.e host = (my host address); and set TLS=true; and in pluggable file i replaced mailer = isMail(); with mailer = isSMTP(); and now am receiving emails for comments. Hope this helps other people with the same issue.
stackexchange-wordpress
{ "answer_score": 0, "question_score": 0, "tags": "email, notifications, smtp" }
How to remove some item from Wordpress Dashboard for user Author I'm trying to remove some item (like 'Commenti') from the WP dashboard for the user Author. I inserted into functions.php this code: add_action( 'admin_menu', 'my_menu_links_removing', 999 ); function my_menu_links_removing() { if ( ! current_user_can('administrator') ) { remove_menu_page( 'comments.php' ); } } The item's name is 'Commenti' (Italian language) and I think that I'm using a wrong string like parameter passed to remove_menu_page function.. Can you help me, please? Thanks in advance!
Two edits: checking for a role is not recommended, you want to check for a capability instead; and the php file you want to pass is `edit-comments.php`. <?php add_action( 'admin_menu', 'my_menu_links_removing', 999 ); function my_menu_links_removing() { if ( ! current_user_can('activate_plugins') ) { remove_menu_page( 'edit-comments.php' ); } } ?> Administrators are the only default role (besides Super Admin if you're on MultiSite) that can activate plugins, so this still checks to see whether the user is an admin, and if not, the comments menu should disappear. See also: < for a list of other menu pages that can be removed and what their php filenames are.
stackexchange-wordpress
{ "answer_score": 1, "question_score": 0, "tags": "functions, dashboard" }
array set title and alt in the_post_thumbnail Using this code: <?php if ( has_post_thumbnail() ) { the_post_thumbnail("mini-me", array( 'class' => 'x-img smpic x-img-circle', 'alt' => the_title(), 'title' => the_title() )); } ?> However, alt and title are being output as text on website instead of enclosed tags. What should the syntax be instead?
Try using `get_the_title` instead of `the_title` \- from the Function Reference: * `the_title` \- Display or retrieve the current post title with optional markup. * `get_the_title` \- Retrieve post title. You might notice that `the_title` says "Display or retrieve" - and it's true, you can pass `false` to the third parameter of `the_title` to get it's output as a return value instead of it `echo`'ing directly to the page, i.e. $mytitle = the_title( '', '', false ); **EDIT** : Updated your code to show this in action: <?php if ( has_post_thumbnail() ) { $title = get_the_title(); the_post_thumbnail("mini-me", array( 'class' => 'x-img smpic x-img-circle', 'alt' => $title, 'title' => $title, ) ); } ?>
stackexchange-wordpress
{ "answer_score": 2, "question_score": 0, "tags": "post thumbnails" }
Hide Featured Image box - isn't working? Currently I have this code in my function file: // REMOVE POST META BOXES function my_remove_meta_boxes() { if ( ! current_user_can('administrator') ) { remove_meta_box( 'tagsdiv-post_tag', 'post', 'advanced' ); remove_meta_box( 'postimagediv', 'post', 'advanced' ); } } add_action( 'admin_menu', 'my_remove_meta_boxes' ); And the tags meta box has been disabled, but not the featured image box. I've looked elsewhere in my functions to see if anything is making it appear again but I cannot seem to find anything. Is there perhaps something I am missing elsewhere?
The context or the 3rd parameter of `remove_meta_box()` function for _tags meta box_ and _featured image meta box_ is `side`. And perfect hook to remove meta box is `add_meta_boxes`. So try the following code, hope it'll work as expected. function my_remove_meta_boxes() { if ( ! current_user_can( 'administrator' ) ) { remove_meta_box( 'tagsdiv-post_tag', 'post', 'side' ); remove_meta_box( 'postimagediv', 'post', 'side' ); } } add_action( 'add_meta_boxes', 'my_remove_meta_boxes' );
stackexchange-wordpress
{ "answer_score": 1, "question_score": 0, "tags": "images, post thumbnails" }
Passing srcset to image attachment method I would like to pass values of `wp_get_attachment_image_srcset` to the `wp_get_attachment_image` method and wonder how is this possible without hardcoding the HTML image tag itself?
I can't say I've tested this but here's what you could to, it should in theory work. The `wp_get_attachment_image()` functions 4th parameter is an array of attributes. You should be able to pass what you get returned from `wp_get_attachment_image_srcset()` to the attribute parameter as follows, _sort of similar_ to the example seen on the docs. $image_attrs = ''; $image_id = 123; $image_size = 'full'; $image_srcset = wp_get_attachment_image_srcset( $image_id, $image_size ); if( ! empty( $image_srcset ) ) { $image_attrs = array( 'srcset' => esc_attr( $image_srcset ), ); } $image_html = wp_get_attachment_image( $image_id, $image_size, false, $image_attrs );
stackexchange-wordpress
{ "answer_score": 2, "question_score": 2, "tags": "images" }
how to add shortcode in wordpress container I develop my plugin with this code : function my_function( $atts ) { some code } add_shortcode( 'myfunction_shortcode', 'my_function' ); I need to use my shortcode on my page or post, when I used it output code shown on top of my page.
This is most likely due to the way your shortcode is constructed. PHP scripts are run on the server before (as) the HTML is generated. Try buffering your shortcode ouput like this: function my_function( $atts ) { ob_start(); // do some stuff $code_output = ob_get_contents(); ob_end_clean(); return $code_output; } More info: <
stackexchange-wordpress
{ "answer_score": 1, "question_score": 0, "tags": "shortcode" }
wordpress show category link instead of post link I'm running WordPress on **localhost** using **XAMPP**. I have a few posts and added them to a specific category (for example cat1 and cat2). I've added the categories to the menu, and when I click on the menu I can see the post names and details. But the issue is the post's URL is same to the category. Look at the image : ![enter image description here]( I want to see post after the click (or hover it). How to solve it?
in the **loop-entry.php** there is `<h2><a href="<?php the_permalink(' ') ?>" title="<?php the_title(); ?>"><?php the_title(); ?></a></h2>` change above code to `<h2><a href="<?php echo get_permalink( $post->ID ); ?>" title="<?php the_title(); ?>"><?php the_title(); ?></a></h2>` Done!
stackexchange-wordpress
{ "answer_score": 0, "question_score": -1, "tags": "posts, categories, get posts" }
Is it possible to enqueue CSS files from plugin before theme's CSS files? If I enqueue styles from my plugin, then it loads after theme's styles. That's why some CSS of my plugin is overriding by theme's CSS. This problem would be fixed if I can ensure my plugin's styles load after theme's styles.
It's easy to add your plugin stylesheet after theme stylesheet. If you're sure that your theme styles and plugin styles have the same selector weight ( _theme has this style`.site-header { background-color: #ccc; }` and your plugin has this `.site-header { background-color: #f1f1f1; }`_) then enqueuing plugin stylesheet after theme stylesheet will work. If you're enqueuing with `wp_enqueue_scripts` action hook then changing the hook priority parameter will do the work. Here's an example: function op_enqueue_scripts() { wp_enqueue_style( 'bootstrap', ' ); } add_action( 'wp_enqueue_scripts', 'op_enqueue_scripts', 50 ); If priority 50 doesn't work then try increasing that to 80 or 100.
stackexchange-wordpress
{ "answer_score": 2, "question_score": 1, "tags": "plugins, plugin development, wp enqueue style" }
Making the HTML list to a checkbox tree with the plugin jstree I would like to make a tree with checkboxes with the jstree plugin. I know I am really close to the solution. I linked everything right, but on my page it only showes the HTML list without tree and checkboxes. Does anyone know what I am missing out, so that the checkboxes work. <title> Hi all</title> <link rel="stylesheet" href="<php echo get_stylesheet_directory_uri(). '/js/jstree/dist/themes/default/style.min.css';?>" /> <div id="data"> <ul> <li>One</li> <li>Two</li> <li>Three <ul> <li>Bike</li> <li>Ride</li> </ul> </li> <li>JOKE</li> </ul> </div> <script src="<php echo get_stylesheet_directory_uri().'/js/jstree/dist/jstree.min.js';?>"></script> <script> $(document).ready(function(){ $('#data').jstree({"plugin":["checkbox"]}); });</script>
This worked for me. Basically jquery was missing through <script src=" </script> and the wrong PHP tags. Thanks for that. You can find the full code below. <title> Hi all</title> <link rel="stylesheet" href="<?php echo get_stylesheet_directory_uri(). '/js/jstree/dist/themes/default/style.min.css';?>" /> <div id="data"> <ul> <li>One</li> <li>Two</li> <li>Three <ul> <li>Bike</li> <li>Ride</li> </ul> </li> <li>JOKE</li> </ul> </div> <script src=" </script> <script src="<?php echo get_stylesheet_directory_uri().'/js/jstree/dist/jstree.min.js';?>"></script> <script src="<?php echo get_stylesheet_directory_uri().'/js/jstree/dist/tree.js';?>"></script>
stackexchange-wordpress
{ "answer_score": 0, "question_score": -1, "tags": "javascript, html, plugin option tree" }
wp_enqueue_scripts is not working in my plugin Here is my code: <?php /* Plugin Name: Awesome Form Validation Plugin URI: Description: Use 'required' class to enable an input as required. Version: 1.0 Author: Abdus Sattar Bhuiyan Author URI: www.facebook.com/abdus.s.bhuiyan */ function awesome_form_validation_scripts() { // wp_enqueue_style( 'awesome_form_validation', get_stylesheet_uri() ); wp_enqueue_script( 'awesome_form_validation', plugin_dir_url( __FILE__ ). '/js/form_validation.js', array(), '1.0.0', true ); } add_action( 'wp_enqueue_scripts', 'awesome_form_validation_scripts' ); Its pretty simple. But after activating plugin I can't see the awesome_form_validation inspecting view page source. Whats wrong with my code?
`plugin_dir_url( __FILE__ )` returns plugin URL with a trailing slash (`/`). So you have to remove the extra trailing slash. wp_enqueue_script( 'awesome_form_validation', plugin_dir_url( __FILE__ ). 'js/form_validation.js', array(), '1.0.0', true );
stackexchange-wordpress
{ "answer_score": 2, "question_score": 1, "tags": "javascript, wp enqueue script" }
PHPCS: Strings should have translatable content I am validating plugin to make it compatible with `WPCS`. a function which contains `gettext` placeholder returning error when i run `phpcs` command. Source code and screenshot of error is attached for reference. Maybe i am missing something or doing it in wrong way? /** * Add Error. * * @package Mypackage * @since 0.1.0 * * @param string $code Error Code. * @param string $message Error Message. * @return object WP_Error Returns Error Object. */ function mypackage_add_error( $code, $message ) { /* translators: %s: Error Message */ return new WP_Error( $code, sprintf( esc_html__( '%s', 'mypackage' ), $message ) ); } **Screenshot of Error.** ![enter image description here](
There are several things wrong with your code 1. The is no need for translation there. The message should have been translated before it is being passed to that function. At that function there is actually no context at all to create any different translation than `%s` 2. Escaping should happen at the output. You should escape the result of the `sprintf` and the translation. And keep in mind that WPCS is a tool to help you, not the bible. At least at its current stage it lacks too many feature to just blindly follow it all the time. Some of the errors it emits right now are due to bad parsing of modern PHP or lacking features, so if you are 100% sure that in your specific case `%s` should be translatable go with it.
stackexchange-wordpress
{ "answer_score": 3, "question_score": 1, "tags": "php, wp cli, coding standards" }
How to access Woo Commerce products from within custom theme? On a custom Wordpress theme, I'm looking to access the product info of products created using the Woo Commerce plugin. Can global product objects be pulled from anywhere within the php files?
Yes you can - see here: < You'd use something like `$myproduct = new WC_Product( $product_id );` Hope that helps
stackexchange-wordpress
{ "answer_score": 1, "question_score": -2, "tags": "woocommerce offtopic" }
Why is my hamburger menu not shown? I use Genesis Digital Pro theme and my responsive menu is not shown on mobile devices. There is block in page that contains my menu, and it opens when you click this area, but I want the hamburger to be shown from the start (as it supposed to work). What to do? ![Screenshot](
The hamburger is shown with ionicons as an `after` element. You have conflicting CSS in your theme. This (specifically, the `content: " ";`) CSS: .entry:before, .entry-content:before, .nav-primary:before, .site-container:before, .site-header:before, .site-inner:before, .wrap:before { content: " "; display: table; } is overwriting the hamburger menu's CSS @media only screen and (max-width: 800px){ .menu-toggle:before, .menu-toggle.activated:before { color: #1e1e1e; content: "\f130"; display: inline-block; font: normal 20px/1 'ionicons'; margin: 0 auto; padding-right: 10px; text-rendering: auto; -webkit-transform: translate(0,0); -ms-transform: translate(0,0); transform: translate(0,0); vertical-align: middle; } } Here's a devtools screenshot: <
stackexchange-wordpress
{ "answer_score": 0, "question_score": -1, "tags": "menus, css, genesis theme framework" }
How do I add more options to the post-new.php page? Some themes have options such as 'enabling or disabling the sidebar', etc, on the post-new.php page. How can I do those (without plugins, I'm making a theme from scratch) ![enter image description here](
The topic is vast, so I'm not going to discuss every detail. In WordPress, there is a concept called **meta box**. Publish, Page Attributes, Featured Image these all are meta boxes. And the good thing is you can create custom meta box. To know how to do that you have to be familiar with `add_meta_box()` function which is one of the many meta box API functions and also the `add_meta_boxes` action hook. Here's an article which will help you to get started <
stackexchange-wordpress
{ "answer_score": 1, "question_score": 0, "tags": "php, posts, screen options" }
Check Password Reset Key Not Woking I am trying create passowrd reset form. Here is my function: <?php $user_data = get_user_by( 'email', '[email protected]' ) ); $key = get_password_reset_key( $user_data ); $user_login = $user_data->user_login; $message = esc_url( get_permalink( '1' ) . "?action=rp&key=$key&login=" . rawurlencode($user_login) ) . "\r\n"; wp_mail( $user_email, "Title", $message ); ?> It sends reset link to my mail, with $key and $login. It is ok. Now i must check the reset key. Here is my code: <?php $errors = new WP_Error(); $user = check_password_reset_key($_GET['key'], $_GET['login']); if ( is_wp_error( $user ) ) { if ( $user->get_error_code() === 'expired_key' ) echo "Key is expired"; else echo "Key is not valid"; } ?> But it always says **Key is not valid**. Where is wrong?
I fixed it. We need decode url with **esc_url_raw**. Here is solution. <?php $user_data = get_user_by( 'email', '[email protected]' ) ); $key = get_password_reset_key( $user_data ); $user_login = $user_data->user_login; $url = esc_url_raw( get_permalink( '1' ) . "?action=rp&key=$key&login=" . rawurlencode($user_login) ) . "\r\n"; $message = $url; wp_mail( $user_email, "Title", $message ); ?>
stackexchange-wordpress
{ "answer_score": 2, "question_score": 2, "tags": "password, reset" }
ACF costum date format I have been working on a WP site and i wanted to add a date for a template. I set up ACF and added a date field to the template and it works but i need my date to be displayed like this: l j F Y. Instead of :dd/mm/yy. I have tried the recommended way that is on the ACF documentation wich looks like this: $date = get_field('date', false, false); $date = new DateTime($date); echo $date->format('l j F Y'); But for some reason this just does not work and disables the rest of the code underneath it.
<?php /* * Create PHP DateTime object from Date Piker Value * this example expects the value to be saved in the format: yymmdd (JS) = Ymd (PHP) */ $format_in = 'Ymd'; // the format your value is saved in (set in the field options) $format_out = 'd-m-Y'; // the format you want to end up with $date = DateTime::createFromFormat($format_in, get_field('date_picker')); echo $date->format( $format_out );
stackexchange-wordpress
{ "answer_score": 2, "question_score": 0, "tags": "templates, child theme, advanced custom fields" }
Loading jquery locally Is there another way than loading jquery through the link: <script src=" I tried this: <?php wp_enqueue_script("jquery"); ?> <?php wp_head(); ?> But when I use wp_enqueue_script("jquery") the local wordpress homepage (with xampp) returns the value NULL
Although it seems like you should be able to just call the function and have it load the script, it's slightly more complicated. Instead, scripts need to be registered and enqueued inside a hook, so they're loaded in the right order. To get jQuery loaded on the front end of your theme wrap the function call inside a callback for the `wp_enqueue_scripts` action. One way is to add this to your theme's `functions.php` file: add_action( 'wp_enqueue_scripts', function () { wp_enqueue_script( 'jquery' ); } ); See < for more info.
stackexchange-wordpress
{ "answer_score": 1, "question_score": 0, "tags": "jquery" }
Please explain how these hooks work I have read about hooks and actions and I know that when we see `do_action('some_hook')` it means that somewhere `add_action('some_hook', function() {...});` or function `some_hook()` exists in a theme's `functions.php`. But what is it?! : From **woocommerce/includes/class-wc-checkout.php** line #943: public function process_checkout() { try { ///////////// do_action( 'woocommerce_before_checkout_process' ); <----!!! if ( WC()->cart->is_empty() ) { throw new Exception( sprintf( __( 'Sorry, your session has expired. <a href="%s" class="wc-backward">Return to shop</a>', 'woocommerce' ), esc_url( wc_get_page_permalink( 'shop' ) ) ) ); } do_action( 'woocommerce_checkout_process' ); <-----!!! I can't find `woocommerce_checkout_process` and `woocommerce_before_checkout_process` anywhere in files! What do they do?
It is possible for action hooks to be provided without being used, which is what's happening here. `woocommerce_before_checkout_process` and `woocommerce_checkout_process` are hooks provided by WooCommerce, but WooCommerce does not itself attach callback functions to either of these hooks. They are provided to allow plugins and themes to run code at the time that the respective hooks are triggered. If you'd like to attach a function to the `woocommerce_checkout_process` hook (for example), you'd add the following code to your theme or plugin: add_action( 'woocommerce_checkout_process', 'wpse_woocommerce_checkout_process' ); function wpse_woocommerce_checkout_process() { // Do something... } This code will run when the line calling `do_action( 'woocommerce_checkout_process' );` in WooCommerce is executed.
stackexchange-wordpress
{ "answer_score": 16, "question_score": 9, "tags": "hooks, actions" }
htaccess rule to ignore specific subdomain I have a .co.uk domain name which hosts a Wordpress website and has SSL certificate applied via AutoSSL in cPanel. I also have a subdomain to that .co.uk which is forwarding to another server using the DNS zone editor in WHM. On the wordpress website, there is a link to the subdomain which should display a web app hosted on the secondary server, but unfortunately it is just reloading the wordpress website, and I am presuming this is something to do with the htaccess file. Is there a rule that needs adding to make the htaccess ignore the subdomain so that when the link is clicked, the user is sent to the subdomain correctly, instead of having it refresh the home page? Thanks
Have asked my hosting support to check my DNS and there were 2 entries because I added an A record in WHM and also added the subdomain to the account in cpanel, they have removed one and all is now working. Apologies for posting in Wordpress, not technically Wordpress related as I first thought.
stackexchange-wordpress
{ "answer_score": 1, "question_score": -1, "tags": "htaccess" }
Bootstrap theme embedded iframes are distorted I'm trying to embed videos onto a page, but they are displaying all stretched out. Here's what it should look like, and this is what it currently looks like. Here's my embed code: <iframe width="100%" src=" frameborder="0" allow="autoplay; encrypted-media" allowfullscreen></iframe> ... but it looks like the default css may be messing with the proportions .embed-responsive-16by9 { padding-bottom: 56.25%; } .embed-responsive .embed-responsive-item, .embed-responsive iframe, .embed-responsive embed, .embed-responsive object, .embed-responsive video { position: absolute; top: 0; bottom: 0; left: 0; width: 100%; height: 100%; border: 0; } Removing the above css makes the video disappear. Any suggestions on why the videos may be appearing to stretched?
You can achieve this by adding some free plugin like this one. This plugin uses FitVids.js to make your videos fluid width. There are many more similar plugins available for free which would allow you to do this without adding any CSS.
stackexchange-wordpress
{ "answer_score": 0, "question_score": 0, "tags": "css, twitter bootstrap, embed, iframe" }
get_post() function returns post even if it is trashed I'm developing a WordPress theme. I am selecting one post as a 'featured post' from the customizer settings. I want to display this post differently on home page. I'm using following code to get the post on home.php: $featured_post = get_post( get_theme_mod( 'featured_post_id' ) ); This code works perfectly to get the post. But, after selecting this post as a featured post, if I trash it, it still gets displayed as a featured post on home page. If I 'Delete it Permanently', it doesn't get displayed. How do I use `get_post()` to get the post that is not trashed?
That's not how `get_post()` works. Trashing the post doesn't change the value of the theme mod, and the theme mod is still going to point to that post in the database, so `get_post()` will dutifully retrieve it as long as it's there. It's up to you to make sure its status is what you want before display: $featured_post = get_post( get_theme_mod( 'featured_post_id' ) ); if ( $featured_post && $featured_post->post_status === 'publish' ) { // Display post } You could also do a `WP_Query` or `get_posts()` (plural) to query posts with the status `publish` _and_ the ID that you have, but it's probably going to end up more lines of code and slightly slower than just checking the status anyway.
stackexchange-wordpress
{ "answer_score": 4, "question_score": 2, "tags": "theme development, themes, trash" }
Historic WordPress database connection Did the WordPress default database connection allow for the use of mysql_query() in years gone by? If so, at what point did this end? Am I assuming correctly that it has to do with the WordPress database object? Background: Many years ago, I wrote a custom template for a WordPress client that involved importing an XML feed into the database and showing it on WordPress pages. I kept copious notes, but only on the trouble areas, and the database connection wasn't one of those. The client moved on, but is now back with an error in that old, old code. I can fix it, but my client is the curious sort and may want specifics on what changed. The error is Warning: mysql_query(): Access denied for user 'root'@'localhost' (using password: NO) in /Address to WordPressTemplate.php on line 38. There is no connection string that I can find, so I'm assuming that this query was using the default WordPress database connection.
WordPress still has `mysql_query()` in its codebase (as of February 27, 2018). `mysql_*()` was deprecated in PHP 5.5.0 and removed in PHP 7.0.0. Since WordPress still supports PHP 5.2 (for reasons beyond understanding), it needs to support both `mysql_*()` and `mysqli_*()`, WordPress will use `mysqli_query()` when available ( PHP > 5.3.0 ) and fallback to `mysql_query()`. If it's the WordPress `$wpdb` object that is using `mysql_query()` it means you're running on PHP 5.2.x, which you really should upgrade. If you're certain you're on PHP 5.3 or greater, then there's some other code that's using the old `mysql_query()`. Although based on the error, it looks like it's a problem with the permissions in your SQL database.
stackexchange-wordpress
{ "answer_score": 4, "question_score": 0, "tags": "database, query" }
Creating a copy of a website in a subdirectory, wp-admin redirect problem I have my Wordpress site installed on a root folder. Then I have a **test** subdirectory where I want to have a copy of my website. I did copy and move all of the files from my main website to the test directory. I have created a new database, a new user, imported the database from the main website into the new database and I have changed the wp_confing.php file in the test directory to use that new database. Everything seems to be ok but when I got to: **mainwebsite.com/test/wp-admin** and I try to log in, it just hangs there, I press on access and I get no error or anything, the password fields just resets but I don't get redirected so I cannot save my permalinks. I suspect an error in the .htacces file, since its' the same from the main website, but then I deleted it and I still have the same problem.
If it's a standard WordPress `.htaccess` file that won't be your problem. I'm willing to bet you forgot to change the Site URL values when you imported the database. You can either edit it in the options table in your database or even in your wp-config file by adding define('WP_HOME', ' define('WP_SITEURL', ' to it. You can read more (or other ways to do it) here: <
stackexchange-wordpress
{ "answer_score": 2, "question_score": 0, "tags": "htaccess, directory, installation" }
How do I check if a posts status is set to draft or pending? I would like to check a posts status, in particular I want to know if a post is set to draft or is privately published. I have the following code: if ('draft' != get_post_status() || is_user_logged_in()) { $this->render(); } else { wp_redirect( site_url('404') ); exit; } It checks to see if a posts status is not set to draft or it checks if they are logged in and then renders either the post or redirects to the 404 page. For some reason privately published posts are visible to non logged in users and I am trying to fix this.
To check post with post status `private`, you could run the following: if (get_post_status() == 'private' && is_user_logged_in()) { // it's private and user is logged in, do stuff } elseif (get_post_status() == 'draft') { // it's draft, do stuff } else { // it's something else, do stuff } Or, in your current setup, you can simply only display _published_ posts via: if (get_post_status() == 'publish') { // it's published, do stuff $this->render(); } You can learn more about post statuses via the codex page.
stackexchange-wordpress
{ "answer_score": 6, "question_score": 2, "tags": "custom post types, posts, post status" }
DISABLE wordpress upgrade page For security purpose I want to Disable the adresse below: ...../upgrade.php It's give informations about the version of wordpress used.
You can actually do this on the web host without actually any PHP code. Using the same procedure as is recommended to deny access to `wp-config.php`, you can also deny access to `upgrade.php`. All you need to do is create a file named `.htaccess` in `wp-admin` and put the following in it: <files upgrade.php> order allow,deny deny from all </files> What this does is it tells the web server software do deny access to `upgrade.php` from everybody. That way if someone tries to access it, the server will return a 403 error instead. This assumes your web host is running Apache as its web server software. If it is not, their support staff should be able to assist you.
stackexchange-wordpress
{ "answer_score": 0, "question_score": 0, "tags": "functions, wp admin, security, upgrade" }
Can't get video meta from wp_read_video_metadata() This is what I'm doing: $video_url = get_field('video_file', $post->ID); $uploads = wp_upload_dir(); $uploads_dir = ( $uploads['basedir'] . $uploads['subdir'] ); $file = $uploads_dir .'/'. basename($video_url); $metadata = wp_read_video_metadata( $file ); The `$video_url` is giving me a URL to video file: < When I `var_dump()` the `$metadata` I'm getting `bool(false)`. The video file exists, it's accessible through URL. I need to get video meta, please help. EDIT: I have require_once( ABSPATH . 'wp-admin/includes/media.php' ); on my custom page and I'm using ACF to get video URL.
To make sure you're getting the correct path to the video, pass the ID to `get_attached_file()`, and use that in `wp_read_video_metadata()`. `wp_upload_dir()` is for getting/creating a directory to write to _now_ , so if the file has not been uploaded in the current month, the path will not be correct if you just add it to the filename. $attachment_id = get_field( 'video_file', $post->ID, false); // Get the raw value, the attachment ID. $file = get_attached_file( $attachment_id ); $metadata = wp_read_video_metadata( $file );
stackexchange-wordpress
{ "answer_score": 1, "question_score": 0, "tags": "custom field, videos" }
WordPress code problem I have this code shown in the picture on top of the search bar. It appears on all pages. ![enter image description here]( I have checked all the plug-ins and it is still there. I don't know what to do next.
This is a shortcode of the Popup builder plugin that for some reason is not being evaluated. Is that plugin installed? Most likely the shortcode is in a widget somewhere. It could also be in a theme file.
stackexchange-wordpress
{ "answer_score": 0, "question_score": 0, "tags": "errors, code" }
Most performant way of fetching remote API data? I am currently trying to speed optimise the fetching of the data via the remote API. I am using it in this way: $response = wp_remote_get(' $response_body = wp_remote_retrieve_body($response); $data = json_decode($response_body, true); It returns an array of data, that I am traversing and saving to appropriate variables with which I later insert the data where I want it to be inserted. All of this is done via AJAX, so that the data is being inserted dynamically. The whole thing takes around 400-600ms. But if I try to access the api endpoint directly with pasting the API URL in the URL bar in my browser it just takes around 50ms. Does the `json_decode` & saving and outputting from variables account to the other 400-500ms? Is there any other way that I could minimase the impact of loading time?
The most performant way of fetching remote API data is **not fetching it at all**. Thus, use Transients API or WP Object Cache to save your computed results for future use and avoid calling external API (and further computations) on every subsequent request. Additionally, fetching, invalidating and regeneration of this data can be done in the background, but that's more of an advanced technique and will heavily depend on your current architecture and specific use case. The 50ms vs 500ms difference comes from: * connecting to your own ajax endpoint * loading and executing part of WordPress engine * connecting, sending the request to external API endpoint and getting the response back (that 50ms, more or less) * parsing the response * your custom computational logic Most time is spent on the first 3 steps, not the last 2. You can profile your code to see the full picture.
stackexchange-wordpress
{ "answer_score": 4, "question_score": 1, "tags": "ajax, api, json, wp remote get" }
How to auto increment post title & post slug field? I've a custom Post Type i.e. `prj` and need to auto increment it's `post_title` (title) and `post_name` (slug) on post save, update regardless of the post status .. the post can never be deleted that's why it won't be an issue .. Need it to behave just like AutoIncrement field in SQL .. once an ID is assigned, it should never be replicated .. So far, I've reached to the code mentioned below .. but the problem is it is only setting up the post title, not the slug and the increment feature is not working as well .. add_filter( 'wp_insert_post_data' , 'odin_prj_title' , '99', 2 ); function odin_prj_title( $data , $postarr ) { if( $data['post_type'] == 'prj' ) { $last_post = wp_get_recent_posts( '1'); $last_post_ID = (int)$last_post['0']['ID']; $data['post_title'] = 'P0' . ($last_post_ID + 1); } return $data; }
I figured out using `wp_count_posts` function, I can get the last total number of posts and save the title at run-time! Added a bit of conditions as well .. add_filter( 'wp_insert_post_data' , 'odin_prj_title' , 10, 2 ); function odin_prj_title( $data , $postarr ) { if( $data['post_type'] == 'prj' && $data['post_status'] != 'publish' ) { $count_posts = wp_count_posts('prj'); $published_posts = $count_posts->publish; $data['post_title'] = 'P0' . ($published_posts + 1); } return $data; }
stackexchange-wordpress
{ "answer_score": 1, "question_score": 1, "tags": "custom post types, wp insert post" }
Add options to the "Screen Options" section on the "Menus" editor I'm working on a system to add custom options to the WordPress menu editor, and I'd like to integrate it with the Screen Options panel. In my research, I couldn't find anything on modifying an existing screen options menu; is this possible? See the screenshots below to better understand what I'm trying to accomplish. Default "Screen Options" on Appearance > Menus: ![default]( Goal "Screen Options" on Appearance > Menus: ![custom](
Figured this out by looking through the WordPress source code function new_site_add_custom_screen_options($args) { $args["custom_option_1"] = __("Custom Option 1", "new_site"); $args["custom_option_2"] = __("Custom Option 2", "new_site"); return $args; } add_filter("manage_nav-menus_columns", "new_site_add_custom_screen_options", 20);
stackexchange-wordpress
{ "answer_score": 2, "question_score": 2, "tags": "customization, filters, screen options" }
Slider loading issue I have uploaded a website I am developing which is here: < and as you can see when the home page first loads the slider has a display glitch and shows it all of the slides before loading correctly. This only seems to happen on the desktop view though. Please can someone take a look and let me know what I can try to fix this?
This is standard behavior with javascript that is deferred or loaded in the footer. All the slides load in, and don't get told to "be sliders" until the whole page has loaded. You can hide them with CSS first: #section-slider .single-slide-wrap { display: none; } And you can have the first slide be shown if you want: #section-slider .single-slide-wrap:first-child { display: block; } Notice the same thing is happening with your `.tab-pane`'s further down the page, so you could add those in as well: #section-services .tab-pane, #section-slider .single-slide-wrap { display: none; } #section-services .tab-pane:first-child, #section-slider .single-slide-wrap:first-child { display: block; } Since the CSS is loaded in the header, the styles will be applied well before the javascript is loaded and kick in.
stackexchange-wordpress
{ "answer_score": 1, "question_score": 1, "tags": "php, jquery, css, javascript, slideshow" }
Change all author links in Blog roll I want all the author links on my blog page to go to a specific url ("/about") instead of the individual author pages. I know this can be done easily with JavaScript, but is there way to do it in functions.php?
did you try: function wpse_author_link( $link, $author_id, $author_nicename ){ return ' } add_filter( 'author_link', 'wpse_author_link', 20, 3 );
stackexchange-wordpress
{ "answer_score": 2, "question_score": 0, "tags": "posts, functions, loop, post meta, author" }
Is there any way to fire heartbeat API from for website visitors? I saw that Heartbeat API is fired when someone is logged in the Wordpress. Is there any way to fire it for website visitors?
As Mark Kaplun says in the comments, you shouldn't do it. But here's how to enqueue the heartbeat script for all users on the public side... if you really, really want to overload your server. add_action( 'wp_enqueue_scripts', 'enqueue_heartbeat' ); function enqueue_heartbeat() { wp_enqueue_script( 'heartbeat', includes_url( js/heartbeat.js ) ); }
stackexchange-wordpress
{ "answer_score": 1, "question_score": 0, "tags": "plugin development, heartbeat api" }
Wordpress mobile and desktop header problems the thing is that in mobile/tabler versions blank white space appears. In desktop version there is no such problem. Moreover, I noticed that if you drag something in mobile version from that blank space, it appears to be a logo from header. I would appreciate any help. My website: www.avizen.lt
The problem either in your theme setting or in css. if the theme setting try make header backround #000 on mobile and align logo center. So that will how your site look on mobile ![enter image description here]( if you write custom css, here is the solution @media screen and (max-width: 767px) { #masthead_TesseractTheme .site-branding { text-align: center !important; } #masthead_TesseractTheme { background: #000 !important; } }
stackexchange-wordpress
{ "answer_score": 0, "question_score": -3, "tags": "headers" }
Get (echo) all role names assigned to user Im trying to do something which I feel should be quite easy but I can't seem to quite grasp. I have the below code which echo's users roles. Great. Fantastic. BUT I have a problem when a user is assigned to multiple roles. It returns null. Can someone please help me? Thanks global $wp_roles; $user_role = implode(', ', get_userdata($user->ID)->roles); echo($wp_roles->role_names[ $user_role ]);
I assume you need a foreach loop and echo each roles name separately. Here's how to do it: global $wp_roles; $user_role = get_userdata($user->ID)->roles; // Check if there is any role for this user if( $user_role ) { foreach ( $user_role as $key => $role ) { echo $wp_roles->role_names[ $role ]; // Add a seperator except for the last name if ( count ( $user_role ) != ( $key + 1 ) ) { echo '/'; } } }
stackexchange-wordpress
{ "answer_score": 3, "question_score": 2, "tags": "user roles, array" }
built-in responsive images in content - do I need to add anything to functions.php? I am making a WP theme from scratch and I don't seem to get the responsive images working. An image that's inserted at 500px will stay at 500px even though srcset and sizes tags are added. From my understanding this image should display automatically at 300px on the mobile phones? <img class="alignleft size-full wp-image-446" src="couple_group_session.jpg" alt="" width="500" height="333" srcset="couple_group_session.jpg 500w, couple_group_session-300x200.jpg 300w" sizes="(max-width: 500px) 100vw, 500px"> ![still displaying at 500px]( Should I be adding something in the Wordpress functions.php file to actually get it working?
Yes as the comment suggests you need to add `max-width:100%; height:auto;` to your img's , you are not containing the image inside the div so there is nothing to tell srcset to use the smaller version.
stackexchange-wordpress
{ "answer_score": 0, "question_score": 0, "tags": "images, content, responsive" }
How to get shared CSS body class between translated WPML pages I need to add the same CSS class to `<body>` element of all translatons of a page, but the CSS class added with `body_class()` is different for each translation because it is taken from the translated title of the page. For example, for _about us_ page I get this markup: <body class="about-us"> // English <body class="sobre-nosotros"> // Spanish I want to get the same class for both languages: <body class="about-us"> // English <body class="about-us"> // Spanish Is there a way to add the same CSS class for all translations of the same page? Thank you.
It's not a good practice to use post name to style your page. Maybe you can use template page. But if you still want to do it, you can do something like this: function add_default_language_slug_class( $classes ) { global $post; if ( isset( $post ) ) { $default_language = wpml_get_default_language(); // will return languague code of your default language for example 'en' // get the post ID in default language $default_post_id = icl_object_id($post->ID, 'post', FALSE,$default_language); // get the post object $default_post_obj = get_post($default_post_id); // get the name $default_post_name = $default_post_obj->post_name; // add default language post name to body class $classes[] = $default_post_name; } return $classes; } add_filter( 'body_class', 'add_default_language_slug_class' );
stackexchange-wordpress
{ "answer_score": 3, "question_score": -1, "tags": "php, css, plugin wpml" }
Unmatch plugin from updates? I have a plugin which I downloaded and removed alot off stuff I don't need from. I also renamed it for simplicity, but right now it is linked to some other plugin, close to the name I gave it. If I go to Plugins under WP-Admin I can press View details. And it brings me information about a plugin with the name I gave it. How do I unmatch this? So that it won't update if that plugins receives an update? Thank you!
Name alone won't match. Name and slug will (slug = folder name that the plugin is in). Name and having the same author line will do the job too. Slug will match all by itself. If you make a custom plugin for your site, name it after your site. Plugin Name: Example.com custom plugin to do whatever We obviously won't have a plugin named after your site, unless you wrote it.
stackexchange-wordpress
{ "answer_score": 0, "question_score": 0, "tags": "plugins, updates" }
Remove Quick edit for custom post type? I have found this thread about the same thing: Remove quick edit for custom post type But I only managed to remove the Bulk edit option with this. What I want to do is to hide/remove Quick edit from a custom post type? How do I manage this?
You can add a filter to the hook named `post_row_actions`. Here's a sample code: (make sure to replace `my-cpt` with the actual post type name) add_filter( 'post_row_actions', 'my_cpt_row_actions', 10, 2 ); function my_cpt_row_actions( $actions, $post ) { if ( 'my-cpt' === $post->post_type ) { // Removes the "Quick Edit" action. unset( $actions['inline hide-if-no-js'] ); } return $actions; }
stackexchange-wordpress
{ "answer_score": 2, "question_score": 0, "tags": "custom post types, customization" }
theme-independent CSS/JS files So far I did the following task to add **theme-dependent** CSS/JS files; I added to the theme's `functions.php` this code, then created the relevant CSS and JS files: function my_theme_enqueue_styles() { wp_enqueue_style( 'parent-style', get_parent_theme_file_uri() . 'style.css' ); } add_action( 'my_theme_enqueue_styles', 'wp_enqueue_styles' ); function my_theme_enqueue_assets() { wp_enqueue_script( 'behavior', get_theme_file_uri( 'behavior.js' ), array(), null, true ); } add_action( 'wp_enqueue_scripts', 'my_theme_enqueue_assets' ); But what if I want my CSS and JS to be **theme-independent**? Say, I want to had a few lines of CSS and JS that will be available in all themes whatsoever. Is there a way to do so in WordPress **outside the WordPress User Interface**?
Use the following code to create a simple plugin. Create a directory `tia` inside `plugins` directory and save the code in a file `tia.php` then put it inside `tia` directory and finally activate from plugin page. <?php /** * Plugin Name: Theme Independent Assets * Author: Obi * Version: 0.0.7 */ if ( ! defined( 'ABSPATH' ) ) { exit; } function tia_enqueue_scripts() { wp_enqueue_script( ... ); wp_enqueue_style( ... ); } add_action( 'wp_enqueue_scripts', 'tia_enqueue_scripts' );
stackexchange-wordpress
{ "answer_score": 1, "question_score": 0, "tags": "theme development, css, javascript" }
WordPress scruity issue - Totally disable all comments by CSS --- secure enough? I have a website in which I want to totally disable, by principle, all comment-publishing windows / all comment functionality. I can give a CSS directive like: #comment-section, .respond {display: none} Is it a secure way of removing any comment functionality?
Obviously that will not remove comment functionality, just will not display relevant comment related data on the front end.
stackexchange-wordpress
{ "answer_score": 1, "question_score": 0, "tags": "comments, security" }
Disable comment windows for all existing posts (pages/blogposts) Is there a WP-CLI command to disable comment windows for all existing posts (pages/blogposts)? I ask this since when I change a theme for a site I have, all pages in that site getting their comment windows again and I need to individually disable comments per each page. In this particular site I have up to 10 webpages but in any case I'd like to that with WP-CLI. Is it possible? If you don't know a way with WP-CLI please at least share another good way you know.
Here is an untested suggestion for wp-cli approach: We can list post IDs of published posts with _open_ comment status with: wp post list --post-status=publish --post_type=post comment_status=open --format=ids and update a post to a _closed_ comment status with: wp post update 123 --comment_status=closed where 123 is a post id. We can then combine those two into: wp post list --post-status=publish --post_type=post comment_status=open --format=ids \ | xargs -d ' ' -I % wp post update % --comment_status=closed or for post_id in $(wp post list --post_status=publish \ --post_type=post --comment_status=open --format=ids); \ do wp post update $post_id --comment_status=closed; done; Then there's the `ping_status` as well to consider. There are other ways than wp-cli but please remember to take **backup** before testing.
stackexchange-wordpress
{ "answer_score": 6, "question_score": 4, "tags": "security, wp cli" }
Only show columns in custom post type? I have a plugin which by default shows extra columns in all columns, not only in that post type. How do I change this code to only show up on this specific plugin page/post type? function modified_column_register( $columns ) { $columns['time_range'] = __( 'Display', 'vs' ); $columns['active'] = __('Active', 'vs'); return $columns; } add_filter( 'manage_posts_columns', 'modified_column_register' ); Thank you! I tried adding this without any luck: $screen = get_current_screen(); if ( 'visitors' == $screen->post_type ) {
Solved it. Changed to manage_{$post_type}_posts_columns and that made it work!
stackexchange-wordpress
{ "answer_score": 1, "question_score": 0, "tags": "custom post types, customization" }
Hide admin notices/notifications from everyone but super admin? I have a Multisite setup, and I would like to hide all notices/notifications from the admin pages for everyone but me (the Super Admin). How would I manage to do this? Thank you!
Try this code in your custom plugin which is better to activate for the network. if ( !is_super_admin() ) { remove_all_actions('admin_notices'); }
stackexchange-wordpress
{ "answer_score": 6, "question_score": 5, "tags": "customization" }
Contact form 7 - How to send mail to two different E-mail Address I am using Contact form 7 plugin for my WordPress website. When User submit the form E-mail is sent to Admin with subject and all the details like name, email, phone, city, zip-code etc..At the same time I also want to send another E-mail to another Admin with fewer details like different subject line and name, email and phone. How to achieve this ??
For your second question (how to send separate email with different info): see the mail2 tab below the first mail entry on the Mail tab. Click the checkbox to get another Mail form where you can set up the second email.
stackexchange-wordpress
{ "answer_score": 0, "question_score": -3, "tags": "plugins, plugin contact form 7" }
Hide devices selection from customizer? Is it possible to hide the device selection from the Customizer. And if it is possible to hide it for a specific User Role, that would be fantastic. I mean this one: ![Picture of device selection in Customizer](
Yes. There is a `customize_previewable_devices` filter which is used to manage which devices are displayed here. For example, to conditionally remove the Tablet device, do: add_filter( 'customize_previewable_devices', function( $devices ) { if ( ! current_user_can( 'do_something' ) ) { unset( $devices['tablet'] ); } return $devices; } );
stackexchange-wordpress
{ "answer_score": 1, "question_score": 1, "tags": "customization, theme customizer" }
how to add custom user capabilities using add_user_meta or something else? i have two WordPress sites with SSO Configurations as described here but the plugin in the answer didn't work for me so i tried to write a code to add capabilities for second site users: $wp_user_query = new WP_User_Query(array('role' => 'author')); $users = $wp_user_query->get_results(); if (!empty($users)) { foreach ($users as $user) { add_user_meta( $user->id, 'orewpst_capabilities', "a:1:{s:6:'author';b:1;}", true ); add_user_meta( $user->id, 'orewpst_user_level', '2', true ); } } the problem is the output result for `"a:1:{s:6:'author';b:1;}"` is `s:23:"a:1:{s:6:'author';b:1;}"` i don't know what "s:23" means and why it appears in database! **update** : I want the string `"a:1:{s:6:'author';b:1;}"` to store in database with out any change! but somehow my code adds an "s:23:" before it.
Try passing the value without serializing it manually, because WordPress will do it for you anyway: add_user_meta( $user->id, 'orewpst_capabilities', array( 'author' => 1 ), true ); or update_user_meta( $user->id, 'orewpst_capabilities', array( 'author' => 1 ) ); // it will create the meta data for you if it doesn't exist already. The `s:23` means that you stored a string with 23 chars. Hope it helps!
stackexchange-wordpress
{ "answer_score": 2, "question_score": 3, "tags": "user roles, user meta, capabilities, user access" }
Automatically check "Allow comments" for custom post type For a custom post type I have enabled support for comments via php and CPT. 'supports' => array( 'title', 'editor', 'revisions', 'comments', ) But each post still has its "Allow comments" box in the discussion-field unchecked. I am now looking for a way to automatically check this box, as I have quite a big number posts of this custom post type and do not think, this can only be done manually. ![]( However, I have other custom post types where I still want comments to be disabled. So I am looking for a way, to check all "enable comments" for one specific post type.
This answer here fixed it for me: < add_filter( 'comments_open', 'my_comments_open', 10, 2 ); function my_comments_open( $open, $post_id ) { $post = get_post( $post_id ); if ( 'myCustomPostType' == $post->post_type ) $open = true; return $open; }
stackexchange-wordpress
{ "answer_score": 5, "question_score": 2, "tags": "custom post types, comments" }
Mustn't do_action be accompanied with a function? Lets say we have a do_action like this: do_action('some_action'); Doesn't this mean that there has to be a `some_action()` function somewhere in the wordpress like this for example: function some_action(){ /* blah blah blah*/ } My question comes from a `do_action()` at the storefront theme of woocommerce that has a line in header.php like this: do_action( 'storefront_header' ); But I haven't been able to find any `storefront_header()` function so I started wondering perhaps not all do_actions are coming with a function of their own. Is it possible?
The param used in `do_action` isn't a function is just a tag that represents the action called, the proper way to use an action is attaching functions with `add_action`. You can learn more from <
stackexchange-wordpress
{ "answer_score": 7, "question_score": 1, "tags": "actions" }
How to use WPML Plugin in contact form 7 I have using WPML plugin in my website for the purpose of translating the content. I have a query how to translate the content within the contact form 7 via WPML plugin. I example : in my contact form have Name, Email, Phone and message fields. So I have set texts before the field (in English). So if clicking the website into another language ( for example , in arabic) , how to change the field identification text such as Name, Email, Phone and Message into Arabic? Please let me know the solution , if any one have done. Thanks
You should create another Contact Form for any different language. You include the form with shortcode, so it's pretty easy to duplicate a form, translate it to given language and then modify the shortcode.
stackexchange-wordpress
{ "answer_score": 1, "question_score": 2, "tags": "plugin contact form 7, plugin wpml" }
Is there any performance consideration when using Custom Post Types? Consider a busy site with about 10,000 posts divided in 10 custom post types. Custom taxonomies and custom fields are also used on all of them. The main query was modified to include all these posts types everywhere, on index, archives, search, feeds. **Now, is there any performance hit caused by using custom post types versus regular 'post'?** Or it wouldn't make a difference what types they are?
No. All posts are stored in the `wp_posts` table. The post type is defined by `post_type` column. Regardless to custom post types included in query, there is only one SQL query executed. Of course there may be some performance hit caused by a little bit more complex query (in vs. =), but it's marginal.
stackexchange-wordpress
{ "answer_score": 2, "question_score": 2, "tags": "custom post types, custom taxonomy, custom field, performance" }
YOAST Seo xmlsitemap menu item not showing in the dashboard 2 days ago I have updated YOAST seo plugin in my WordPress website. All of a sudden the xml sitemap menu disappeared from the dashboard following this update. Any one have any thoughts? Note:I do not think so this is because of any conflict between other plugins or theme as it was working fine till 2 days ago. ![enter image description here](
Yoast Seo was changed their options in version 7.0. Sitemap was one of their changes.If you need to exclude some post,pages,etc from sitemap, you need to set it as noindex More info here
stackexchange-wordpress
{ "answer_score": 1, "question_score": 0, "tags": "plugins, plugin development, plugin wp seo yoast" }
Get woocommerce product price by id i make one shortcode for get product title, image and price. i am getting all title, link and image properly but not getting price. but problem is add_shortcode('product_data','custom_product_function'); function custom_product_function($atts) { $post_id = $atts['id']; $title = get_the_title($post_id); $link = get_the_permalink($post_id); $price = get_the_price($post_id); $image = get_the_post_thumbnail($post_id, 'thumbnail'); $data ='<div class="releated-products wow fadeInUp"><a href="'.$link.'">'.$image.'<h5>'.$title.'</h5><h6>'.$price.'</h6></a></div>'; return $data; } `$price = get_the_price($post_id);` i guess this function not correct any idea how to get price now. Thanks you
You can create a product object using the following function: `$product = wc_get_product( $post_id );` And after that you will be able to access to all product's data. All available methods can be found here, but the ones you need are: $product->get_regular_price(); $product->get_sale_price(); $product->get_price();
stackexchange-wordpress
{ "answer_score": 45, "question_score": 17, "tags": "woocommerce offtopic" }
Wordpress theme with frontend in different language than backend? I have added the po and mo files via Poedit for Chinese to my wordpress site. I would like to keep my backend in English. How can this be achieved? Is this possible without using a plugin such as Polylang? ![English Wordpress Admin plugin](
I used to use WP Native Dashboard. But I just tested it and it's not working. So I tested a plugin for you and I found one that really works, it's English WordPress Admin, after you activate it you will see this, you click on Switch to English and it will update your dashboard Language, mine was Spanish and it changed to English as expected. ![enter image description here](
stackexchange-wordpress
{ "answer_score": 0, "question_score": 1, "tags": "localization, language" }
How to find the output of contact form 7 shortcode? I'm working on the website which is using contact form 7 and in that form they are using shortcode to display their own number, like so: <fieldset class="precallback"> <legend class="top-section">Ring til os</legend> <ul class="formlist"> <li class="textonly">Vita 34's kundeservice besvarer alle spørgsmål om stamceller fra navlesnoren. Vi ringer også gerne til dig i vores kontortid.<br />Rådgivning fra mandag til fredag 09.00 - 15.00<br /> [klickbarestelefon] </li> <li class="textonly">Ja, ring venligst tilbage</li></ul> </fieldset> But I just can't find where that `[klickbarestelefon]` comes from. I searched the whole admin panel, and database but couldn't find the output of it. Is there a way to find and change the output of this shortcode?
If you have FTP access (or the **WordPress** files) go to `wp-content` and search within that folder for a file that contains `klickbarestelefon`. You will find the file where the shortcode was created. You add shortcodes on **WordPress** using this syntax: add_shortcode("shortcode_name", "function_name")
stackexchange-wordpress
{ "answer_score": 1, "question_score": 2, "tags": "php, shortcode, database, plugin contact form 7" }
remove_action() not working in page template - Genesis I've had a good look around but can't find anyone with the same specific problem. In _functions.php_ I'm adding the following actions: add_action( 'genesis_entry_header', 'twl_content_wrap_start', 15 ); function twl_content_wrap_start() { echo '<div class="container">'; } add_action( 'genesis_entry_footer', 'twl_content_wrap_end', 15 ); function twl_content_wrap_end() { echo '</div>'; } Then in my Page Template _page_full-width.php_ , I'm trying to remove these actions. remove_action( 'genesis_entry_header', 'twl_content_wrap_start', 15 ); remove_action( 'genesis_entry_footer', 'twl_content_wrap_end', 15 ); But it's not working! Any Ideas? Thanks
Page templates are called too late to effect actions. You can achieve what you need another way, by targeting this in your functions, with a test for the page template, like this: function twl_content_wrap_start() { if ( !is_page_template( "page_full-width.php" ) ) return '<div class="container">'; } BTW, as a rule of thumb, actions generally don't `echo`, they should `return` (although it does depend on the action).
stackexchange-wordpress
{ "answer_score": 0, "question_score": 0, "tags": "php, functions, actions, page template" }
How to implement content from external database into Wordpress text page? What methods exist to implement data values from external database into a Wordpress text page? I think that there are two possible ways but maybe there are some more ways to realize this? * Maybe there exists a WordPress Plugin? - I've tried to find one, but without luck. I don't know the keywords how to find one. The < PHP code widget allows using PHP Code but only in Widgets, not in text. * Second idea to integrate data values into WordPress page is to use iframes. Not sure, if this is a good and practical idea. I have made a sketch to better illustrate what I want to realize: ![Data from external Database]( May you know some different ways to realize this?
You should write a plugin, or compact the code needed for this in a child theme `functions.php`. About pulling data from external databases: the simplest way is to use php built-in functions. I would proceed this way: 1. Register a shortcode to place your table wherever you want in Wordpress, you probably want to pass some values, to select the specific data you want to pull from the database or the look the table should have 2. Hook the shortcode to a function, that connects to the external db and queries it, according to your needs, builds a table using the data and outputs it. Resources: Wordpress Shortcodes, Html table output via php
stackexchange-wordpress
{ "answer_score": 3, "question_score": 0, "tags": "database, post content, customization" }
Update the permalink for one post via wp cli I'm using WP-CLI to import articles from a non-WordPress system. The legacy system has a custom URL defined for every post. I'd like to be able to set the permalink on the posts I'm importing base on the custom URL defined in the legacy system. I don't need to set the entire permalink, just being able to set the suffix, as is supported in the WP admin UI, would be sufficient. But there doesn't seem to be a way to change the permalink for a specific post using WP-CLI. Am I missing something?
If you mean the _post name_ field, then we can update it for a post with: wp post update 123 --post_name="new-slug" where 123 is the post ID. If we then try to update another post with the same post name: wp post update 321 --post_name="new-slug" then it will be set to `new-slug-2` in that case, as it needs to be unique. If we continue this with other posts, then we will get `new-slug-n` where `n` is a positive integer.
stackexchange-wordpress
{ "answer_score": 6, "question_score": 1, "tags": "permalinks, wp cli" }
CPT Template Option to Top I edited the following core file because I was unable to make the change in my child theme. I need my CPT Template option to appear first in the Post Attributes -- Template drop down list. I made it happen by editing: .../wp-admin/includes/meta-boxes.php, within the "default_page_template_title" filter. I switched the order of two lines making my CPT Template appear on TOP. <?php page_template_dropdown( $template, $post->post_type ); ?> <option value="default"><?php echo esc_html( $default_title ); ?></option> </select> How would I do this in the child theme? Thank you
You could hook into theme_{$post_type}_templates and add an identical "default" option at the end: add_action('theme_page_templates', 'wpse_296283_theme_page_templates'); function wpse_296283_theme_page_templates($post_templates){ $post_templates['default'] = "Default Template"; return $post_templates; } Then you'd hide the first one with CSS: add_action('admin_head' 'wpse_296283_admin_head'); function wpse_296283_admin_head(){ ?> <style>#page_template option:first-child {display: none;}</style> <?php }
stackexchange-wordpress
{ "answer_score": 1, "question_score": -1, "tags": "custom post types, templates, metabox" }
Create sub-domain for multisite and multi languages? I have developed multisite in WordPress. I have created two multisite one for Hindi and another for English. Hindi URL is: ` and English URL is: ` Now my requirement is the URL for Hindi should like ` and for English, it should be a default URL like ` Thanks
There are two ways to setup a multisite network, using subdomains and using subdirectories. Your current setup is for subdirectories and to change the URLs the way you want them you‘ll need to change the setup to use subdomains. This is a great article explaining the difference between those two setups and how to change from subdirectories to subdomains: < **Beware** that to setup WordPress multisite to use subdomains you’ll need to use wildcard subdomains. Make sure your hosting provider can set that up for you.
stackexchange-wordpress
{ "answer_score": 2, "question_score": 0, "tags": "multisite, multi language" }
Placeholder in HTML editor text area? I am trying to make a placeholder appear on the default html editor on a specific post type. The code looks like this: add_filter('the_editor','add_placeholder_event'); function add_placeholder_event( $html ){ if ( 'event' == $post->post_type ) $html = preg_replace('/<textarea/', '<textarea placeholder="my place holder text" ', $html); return $html; } It does not work, however, if I remove `if ( 'event' == $post->post_type )` from the code it will work (but will apply to every html text editor on Wordpress). Any idea what I am doing wrong?
Solved it: function add_placeholder_event( $html ){ $screen = get_current_screen(); $post_type = $screen->post_type; if( $post_type == 'event' ) { $html = preg_replace('/<textarea/', '<textarea placeholder="John Doe" ', $html); } return $html; } add_filter('the_editor','add_placeholder_event');
stackexchange-wordpress
{ "answer_score": 3, "question_score": 1, "tags": "custom post types, customization, html editor" }
Filter out results from REST API I want to build a plugin to remove all posts by specific users from rest json output. How can I add a **filter** or **hook** to do that?
If you're using WP 4.7+ you can filter the query using the `rest_{$this->post_type}_query` hook `wp-includes/rest-api/endpoints/class-wp-rest-posts-controller.php:L267` This is a working example that filters current query by given terms $types = [ 'post', 'page', ]; foreach ( $types as $type ) { add_filter( 'rest_' . $type . '_query', 'filter_rest_query_by_zone', 10, 2 ); } function filter_rest_query_by_zone( $args, $request ) { $zones = [ 'term1', 'term2', 'term3' ]; $args['tax_query'] = array( 'relation' => 'AND', array( 'taxonomy' => 'zones', 'field' => 'term_id', 'terms' => $zones ) ); return $args; }
stackexchange-wordpress
{ "answer_score": 3, "question_score": 4, "tags": "plugins, hooks, rest api" }
Force Code (Appearance) Editor to Use Spaces Not Tabs We use SASS when building custom themes, and sometimes clients need a quick change made which is easier to do on the server rather than locally and pushing new changes. To that end, we've installed SASS on our server to watch for file changes. The problem is, if we use the WordPress Appearance Editor to edit SASS files, it defaults to tabs instead of spaces and we use spaces in the office. So SASS compiler (transpiler?) throws an error. Is there any way to force the WordPress Appearance Editor to use Spaces instead of Tabs? I tried a quick search but everything seemed to be related to the WYSIWYG editor in pages/posts.
The WordPress theme/plugin (file) editor uses CodeMirror for syntax highlighting, and with the hook `wp_enqueue_code_editor` (which is available starting from WordPress version 4.9.0), you can filter the default CodeMirror settings, as in the following example: add_filter( 'wp_code_editor_settings', function( $settings ) { $settings['codemirror']['indentUnit'] = 2; $settings['codemirror']['indentWithTabs'] = false; return $settings; } ); See < if you'd like to change other CodeMirror settings. PS: You'd add the code above to the theme's _functions.php_ file.
stackexchange-wordpress
{ "answer_score": 3, "question_score": 0, "tags": "sass" }
Wordpress database connection My site was hacked and I have loaded everything back up but the pages, posts, images etc are not showing on the site. I have noticed in my database ameqt_wp507 it has a list saying wp_507posts etc and another that says wp6t_posts etc. The one with wp6t has all the content in it. How do I make it look at that info? Thanks Sarah ![enter image description here](
Check your wp-config.php file and look for the table prefix. That should be wp6t_.
stackexchange-wordpress
{ "answer_score": 2, "question_score": 0, "tags": "database" }
What is the best security $_POST method? I made profile page. And i am getting values directly from inputs with $_POST method. Users update their profile in this page. I wonder is this security method? And i am using this in wp_list_table too.
You have to sanitize or escape the data based on type and application of the data. Like below- $title = sanitize_text_field( $_POST['title'] ); update_post_meta( $post->ID, 'title', $title ); It's a quite huge topic. You better read this Validating Sanitizing and Escaping User Data.
stackexchange-wordpress
{ "answer_score": 3, "question_score": -1, "tags": "security" }