INSTRUCTION
stringlengths
11
999
RESPONSE
stringlengths
0
999
SOURCE
stringlengths
16
38
METADATA
dict
How to allow registration only from a certain location? I'm currently working on a Multivendor eCommerce based on Woocommerce (and Multivendor plugin like: Dokan/WP Marketplace/WP Vendor). I need to allow vendor registration just from a country in the world and exclude it from any other. Currently, I haven't even been able to understend where to look for: I just need to know where I should be watching out to gain a solution, and I'll be finding the code by myself.
The googles suggested several ways to do this, either with PHP or jQuery. Here's one article I found to get you started: < Plus there is this Stackoverflow answer that might help: < "Geolocation" is a good search term to use. You'll need to customize you registration form to enable this, but perhaps these links will help. Good luck.
stackexchange-wordpress
{ "answer_score": 0, "question_score": 0, "tags": "woocommerce offtopic, e commerce" }
Does the order of sections in readme.txt matter? As the title says, _Does the order of sections in readme.txt matter?_ This relates to me editing changelog every update and having to scroll past all the FAQ entries. Is it OK to move changelog to the top of readme.txt to make my life just that little bit easier?
Only header ( === Plugin name === ) and short description ( in that order ) must be on top. Other sections ( == section == ) can be placed in any order. Your == Changelog == can go just below short description, not higher.
stackexchange-wordpress
{ "answer_score": 1, "question_score": 1, "tags": "plugin development, readme" }
Wordpress network (multisite) /wp-admin/ redirect loop (ERR_TOO_MANY_REDIRECTS) I have a Wordpress network where I run +/- 10 sites. Recently, I got a redirect error when accessing the wp-admin page for one of the sites. All sites in the network are working fine, I can also access their admin without any issue except for one site. I get the error: ERR_TOO_MANY_REDIRECTS Here is what I have done: * clean all my cookies * clean cache in browser, server and cloud * rename htaccess * rename plugin folder * rename theme folder * add define('COOKIE_DOMAIN', false); to wp-config This site has exactly the same configuration as the others, I don't understand why I can't reach my admin page. Do you have any idea? Thanks Laurent
I have been experiencing exactly the same thing. I run 5 Wordpress sites on the same server, but suddenly started getting ERR_TOO_MANY_REDIRECTS when I try to access wp-admin on one of them (the others are fine). If I delete .htaccess entirely in that domain's subdirectory I can access the admin panel again, similarly if I delete the Wordpress code from the top of the .htaccess file (although then I lose the redirects for pretty permalinks). Having consulted with my host, they advised me that it may be an issue with using SSL and Cloudflare. Once I disabled Cloudflare everything returned to normal. I have now changed the Cloudflare SSL support to 'Full Strict' and am waiting for it top propagate.
stackexchange-wordpress
{ "answer_score": 1, "question_score": 2, "tags": "multisite, wp admin, redirect" }
How to enqueue an external Javascript file to Frontpage footer I am trying to add an external Javascript file from my plugin. My code is - <?php /****** * * Plugin Name: Image Zoom * Author: Kallol Das * Description: This plugin will zoom an image of WordPress posts. * version: 1.0 * *******/ function zoom_image_main_js_init(){ wp_enqueue_script('zoom-script', plugins_url('/js/zoom-script.js', __FILE__), array('jquery'), 1.0, true); } add_action('init', 'zoom_image_main_js_init'); Now the problem is It's only enqueuing in admin footer But not in Frontpage footer. So, how to do that?
Instead of `init` use `wp_enqueue_scripts`, which is used to enqueue styles and scripts in front-end. Also, for backend enqueue use `admin_enqueue_scripts`.
stackexchange-wordpress
{ "answer_score": 0, "question_score": 0, "tags": "plugin development, wp enqueue script, footer" }
Get all post from a post type For a custom plugin I want a full list of all products we have in WooCommerce. So, I found this code, but it shows only 10 results, instead of all products. $loop = new WP_Query( array('post_type' => 'product', 'post_per_page' => -1)); What is the right loop to get all products?
You can try this: $options = array('post_type'. => 'product', 'post_per_page' => -1, 'nopaging' => true, ) $loop = new WP_Query( $options ); This adds `'nopaging' => true,`. See Class_Reference/WP_Query#Pagination_Parameters for more info
stackexchange-wordpress
{ "answer_score": 1, "question_score": 0, "tags": "custom post types, wp query, woocommerce offtopic" }
strip_tags in get_the content So, I tried to strip all the html tags in a string but I can't get it to work. This is my code snippet $content = get_the_content(); $content = preg_replace("/<embed[^>]+\>/i", "(embed) ", $content); $content = apply_filters('the_content', $content); $content = str_replace(']]>', ']]>', $content); echo wp_strip_all_tags($content);
$content = get_the_content(); // regex (fixed) replacing '<embed>' with '(embed )' $content = preg_replace("/<embed?[^>]+>/i", "(embed) ", $content); // remove all tags $content = wp_strip_all_tags($content); echo $content; **Edited according to the first comment:** What you are trying to remove are not tags, these are HTML character entities. E. g., `<p>` was converted to `&lt;p&gt;` by WordPress when you've saved the content in the visual editor. You have two choices: 1. edit the content in the built-in text editor to remove those entities (switch the editor from _Visual_ to _HTML_ mode); 2. use different regexes to remove entities after the post was fetched. For example (not tested, but you have the idea): $content = preg_replace("/&lt;embed?[.]+&gt/i", "(embed) ", $content); $content = preg_replace("/&lt;[.]+&gt/i", "", $content);
stackexchange-wordpress
{ "answer_score": 1, "question_score": 1, "tags": "the content" }
How to integrate CAPTCHA on register page? How can I integrate CAPTCHA on my register page to prevet bots to register (to prevent them from submiting the form).
You may search install a pluggin like No CAPTCHA. Supports: Contact Form 7, Ninja Forms, Gravity Forms, MailChimp, Formidable forms, WooCommerce, JetPack comments and contact form, BuddyPress, bbPress, Fast Secure Contact form, S2Member, MailPoet, any WordPress registrations & contact forms and themes.
stackexchange-wordpress
{ "answer_score": 1, "question_score": 0, "tags": "user registration, captcha" }
How to create an endpoint without creating sub endpoints? I'm trying to create a new endpoint using `add_rewrite_endpoint()`. Here's my code: // Add query var. add_filter( 'query_vars', function( $vars ) { $vars[] = 'my-endpoint'; return $vars; } ); // Add endpoint. add_action( 'init', function() { add_rewrite_endpoint( 'my-endpoint', EP_AUTHORS ); } ); I can now visit example.com/author/my-endpoint which is great but "sub" endpoints also seem to work. For example: * example.com/author/my-endpoint/random * example.com/author/my-endpoint/anything-here How can I create my endpoint **without** also creating these "sub" endpoints?
The rewrite rule added by: add_rewrite_endpoint( 'my-endpoint', EP_AUTHORS ); is author/([^/]+)/my-endpoint(/(.*))?/?$ => index.php?author_name=$matches[1]&my-endpoint=$matches[3] so it assumes anything after e.g. `/author/henrywright/my-endpoint/...`. You can try instead to replace it with `add_rewrite_rule()` e.g. add_rewrite_rule( '^author/([^/]+)/my-endpoint/?$', 'index.php?author_name=$matches[1]&my-endpoint=1', 'top' );
stackexchange-wordpress
{ "answer_score": 2, "question_score": 2, "tags": "url rewriting, endpoints" }
Custom Login page with custom redirects for each user? I've seen a few different plugins that help with custom redirect upon login, but I think some deal with the initial wordpress login. I have a 'portal' now that displays certain info and I've duplicated it into 4 different modified versions: SuperAdmin, Admin, Billing, GPI. When the user is on the main site and they click the 'Portal' Nav link, I want that to direct to a custom login page and depending on the role/credentials I want to redirect the user from there to one of the 4 pages. Is there a way that anyone knows of that is best for this type of request? Perhaps a plugin that allows for creation of the login page/form as well as custom redirects?
I think you need this plugin: < Anyway check out this post: <
stackexchange-wordpress
{ "answer_score": 1, "question_score": 0, "tags": "plugins, users, user roles" }
pre_get_posts - Trying to get property of non-object warning This code outputs the following warning when run on the `pre_get_posts` action: `Trying to get property of non-object` Which points to this line: `if( 'edit' == $screen->base && 'my_post_type' == $screen->post_type && $order_by == '0' ) {` Why am I getting this warning? public function my_post_type_default_sort( $query ){ if( !is_admin() ) { return; } $screen = get_current_screen(); if( !isset( $_GET['orderby'] ) ) { $order_by = '0'; } if( 'edit' == $screen->base && 'my_post_type' == $screen->post_type && $order_by == '0' ) { $query->set( 'orderby', 'scr_date' ); $query->set( 'order', 'ASC' ); } }
`$screen` may not be available yet when `pre_get_posts` fires. Try this instead: public function my_post_type_default_sort( $query ){ if(!isset($_GET['orderby']) && is_admin()) { $orderby = '0'; } if($query->is_main_query() && is_admin() && is_post_type_archive('my_post_type') && $orderby=0) { $query->set('orderby','scr_date'); $query->set('order', 'ASC'); } }
stackexchange-wordpress
{ "answer_score": 2, "question_score": 0, "tags": "wp query, query, pre get posts" }
Changing permalink structure and domain Who could help me with the following: I am moving my site to another domain AND I want to change my permalink structure. I wish to edit my .htaccess file of my OLD domain. So: < SHOULD BE 301 REDIRECTED TO < All my old URL's should be 301 redirected to the new URL's and new permalink structure. What are the necessary steps I should take?
on your **old domain** add this following rule at the top of .htaccess RedirectMatch 301 ^/([0-9]{4})/([0-9]{2})/(.*)$ plase let me know if its work or not.
stackexchange-wordpress
{ "answer_score": 1, "question_score": 0, "tags": "permalinks, domain" }
remove specific classes from menu items I want to remove some specific class names from the menu items For example I need to remove classes of `fa` and `fa-desktop` from all menu items in WordPress <li id="menu-item-21" class="dropdown-header fa fa-desktop menu-item menu-item-type-taxonomy menu-item-object-category menu-item-has-children dropdown col-sm-4 menu-col menu-item-21 dropdown"> Thank you
add_filter('nav_menu_css_class', 'special_nav_class', 10, 2); function special_nav_class($classes, $item){ if(($key = array_search('fa', $classes)) !== false) { unset($classes[$key]); } return $classes; }
stackexchange-wordpress
{ "answer_score": 3, "question_score": 0, "tags": "menus, filters, navigation" }
Categories not shown in admin after adding woocommerce products via wp wc cli After the following script is run wp wc product create --name='b' --categories=32 --user=user Output is printed: Success: Created product 1370. But no categories are shown in wp-admin/WooCommerce->Products page for the newly added product. I have followed Find Product Category IDs to get category id. Tried to use [32], ['32'] instead of 32. The result is the same. Category is not shown in wordpress admin. How to fix it?
After opening issue on woocommerce github page and authors reaction. The solution is wp wc product create --name='Product Name' --categories='[ { "id" : 21 } ]' --user=admin
stackexchange-wordpress
{ "answer_score": 1, "question_score": 2, "tags": "woocommerce offtopic, wp cli" }
Adding A New Widget to Wordpress Disables the Existing Widgets I need to add four sidebar widgets that display on designated pages. When I add the code to create the new widgets to the functions.php, it disables the other widgets. The footer widget, and one of the existing sidebar widgets stops working. They still appear in **Appearance -> Widgets** , but on the website they stop displaying. Here is the code I used to add the widget. if ( function_exists('register_sidebar') ) { register_sidebar(array( 'name' => 'Sidebar About', 'id' => 'about-sidebar', 'description' => 'Sidebar that shows only on the About page', 'before_widget' => '<li id="%1$s">', 'after_widget' => '</li>', 'before_title' => '<h2>', 'after_title' => '</h2>', )); } I am worried that my clients website has too many plugins that may interfere with creating new widgets.
You missed a lot of things . You have to add add action hook in your code. In below I give you an ideal widget code. Now try this.Replace your code with mine. Hope it will work. Thanks function test_widgets_init() { register_sidebar( array( 'name' => esc_html__( 'Sidebar', 'test' ), 'id' => 'sidebar-1', 'description' => esc_html__( 'Add widgets here.', 'test' ), 'before_widget' => '<section id="%1$s" class="widget %2$s">', 'after_widget' => '</section>', 'before_title' => '<h2 class="widget-title">', 'after_title' => '</h2>', ) ); } add_action( 'widgets_init', 'test_widgets_init' );
stackexchange-wordpress
{ "answer_score": 0, "question_score": 0, "tags": "functions, customization, widgets" }
looking for indoxploit hack solution On our WordPress powered website we have only 1 user: ID: 1 username: is not admin WordPress working with latest version, theme and plugins are all updated to the latest. username and password is hacked and both set to indoxploit I have reset username and password by phpMyAdmin i googled < it seems there is an exploit named indoxploit Please advice how can I prevent this hack?
I fixed it by BBQ: Block Bad Queries plugin: <
stackexchange-wordpress
{ "answer_score": 0, "question_score": 0, "tags": "hacked" }
Add 'page template' column to dashboard for CPTs How can I add a 'Page Template' column to the Dashboard, so that viewing 'All cpt_name' shows which template is used.
<?php // add new column to the columns array function wpse267793_columns($columns) { // Column name $columns['template'] = 'Template file'; return $columns; } function wpse267793_show_template_columns($name, $post_id) { // get template file name from post meta $template = get_post_meta($post_id, '_wp_page_template', true); echo $template; } // change 'CPT' to the relevant custom post type add_filter('manage_CPT_posts_columns', 'wpse267793_columns'); add_action('manage_CPT_posts_custom_column', 'wpse267793_show_template_columns', 10, 2); * manage_posts_custom_column * manage_posts_columns
stackexchange-wordpress
{ "answer_score": 1, "question_score": 0, "tags": "custom post types, admin" }
The wp_enqueue_scripts hook doesn't work at all, not from plugin, not from the template, not for frontend, not for admin pages! I tried everything and my action hook wp_enqueue_scripts doesn't work! What can stop it from working? This is my code inside the plugin. The plugin is activated: function wpb_adding_scripts() { error_log("try 9"); } add_action ('wp_enqueue_scripts', 'wpb_adding_scripts');
The `wp_enqueue_scripts` function is hooked to run on the `wp_head` action, which is triggered by the `wp_head()` function. This function should be placed within the `<head>` tag of your theme's markup. If we refer to the core file `default-filters.php`, we can see the many functions that rely on `wp_head` for output.
stackexchange-wordpress
{ "answer_score": 4, "question_score": 2, "tags": "wp enqueue script" }
Creating a navigation link to my front-page I have a menu linking to each of my pages, but I cannot seem to get the link to my front-page working...What is the correct way in Wordpress to link back to your front-page? This works for all of the other pages, just not for my front-page: <a href="<?php echo get_page_link( get_page_by_title( 'Home Page' )->ID ); ?>"> Home. </a> My front-page template does have the "Home Page" name so I'm not sure why this works with all of the other pages but not this one.
You can use `home_url()`, which will point to the Site URL regardless of reading settings and/or what page it is: echo esc_url( home_url( '/' ) );
stackexchange-wordpress
{ "answer_score": 3, "question_score": 1, "tags": "links" }
How to populate a Mailchimp newsletter with latest events from Wordpress plugin EventOn? Once a month I send a newsletter with upcoming events. I also publish all the event on a wordpress site with EventOn. I was wondering if there is a way to import the latest events in a mailchimp newsletter. Now I enter all the events manually, which is tedious. Any tips welcome. :)
The easiest way to accomplish this would be to get an RSS feed from EventOn and then create an RSS Campaign in Mailchimp and pull in the event items automatically using that RSS feed. * Configuring RSS Feed in EventOn * Using RSS Content Blocks in Mailchimp PS This is really not the right forum for this question, but hope this helps :)
stackexchange-wordpress
{ "answer_score": 0, "question_score": 0, "tags": "plugins, events, automation, plugin mailchimp" }
How can I get logged in user's session data from admin-ajax? I have hooked an ajax call for a logged-in user, and now I need to catch his data inside the receiving call (the code that receives the action call). How can I get the user's ID reliably? This code is inside my plugin definition file and the code inside the function (error_log("we're in....kind of");) is being called: add_action( 'wp_ajax_create_team', 'create_team' ); function create_team() { error_log("we're in....kind of"); } }
`wp_get_current_user` will get you the `WP_User` object for the currently logged-in user: add_action( 'wp_ajax_create_team', 'create_team' ); function create_team() { $current_user = wp_get_current_user(); echo $current_user->ID; die; }
stackexchange-wordpress
{ "answer_score": 3, "question_score": 4, "tags": "ajax, admin, session" }
How to Remove Two (Related) wp_postmeta Rows? I have entries in wp_postmeta like so (shortened for brevity: > **post_id | meta_key | meta_value** > > integer | _thumbnail_id | integer > > integer | rafi | integer Now it's easy to select and delete all rows containing _thumb. Same with rows containing rafi. What I need to do is delete the rows with a common post_id AND both _thumb and rafi. The reason is I only want to remove the featured image from posts that have the rafi key set. I can delete matching _thumbnail_id rows thusly: > global $wpdb; > > $wpdb->query( " > > > DELETE FROM $wpdb->postmeta > > WHERE meta_key = '_thumbnail_id' > > > " ); But I am not sure how to proceed in terms of doing the proper selecting of the matching rows to set up the deletion. Thanks for any ideas!
After 5 hours of searching finally I wrote the SQL query and that is- DELETE FROM {$wpdb->postmeta} WHERE post_id IN (SELECT post_id FROM (SELECT post_id FROM {$wpdb->postmeta} WHERE meta_key LIKE '_thumbnail_id' AND post_id IN(SELECT post_id WHERE meta_key LIKE 'rafi')) AS s) I saw your answer above, but using this kinda `SQL` query for this kinda problem is best practice as well as better. Hope this helps.
stackexchange-wordpress
{ "answer_score": 3, "question_score": 2, "tags": "post thumbnails, mysql" }
Custom Search for Drafts in Custom Post Type Is it possible to create a search page that will search for a keyword only in a custom post type that has the status "draft?" Basically, I have a lot of data I was planning on importing as a custom post type. The data would be simple, "name", "answer", "notes." However, I don't want this data published because each custom post would have almost no data and the site would then have 5,000 spammy pages. However, users frequently want to know the "answer" for certain "names," and I need to give them the ability to search and find.
It's possible to search within drafts by setting the `post_status` argument to `draft` in your search query, however, a better option is to control things with the arguments passed to `register_post_type`. We first set `public` to false, which will hide the post type everywhere- front and back end. We then selectively enable `show_ui` to get the admin UI, and set `exclude_from_search` to `false` so they show up in front end searches. We also set `rewrite` to `false`, so WordPress doesn't generate rewrite rules for this post type. You will then have published posts that are searchable, but they will have no individual pages on the front end. $args = array( 'public' => false, 'show_ui' => true, 'exclude_from_search' => false, 'rewrite' => false, 'label' => 'Name', // your other arguments... ); register_post_type( 'name', $args );
stackexchange-wordpress
{ "answer_score": 2, "question_score": 1, "tags": "custom post types, search, draft" }
Meta tag viewport I made my very own WordPress theme from scratch and I don't use a header nor a footer for it (so no header.php or footer.php files present). All of the important content is directly in the index.php file. So I was wondering where I can put my meta tags in. Specifically this meta tag, <meta name="viewport" content="width=device-width, initial-scale=1.0"/> I'm currently making my theme responsive and so far, all my css media queries are not working at all. Can I just put it in my index.php file or do I have to set up a function in the functions.php file? Thanks for any help!
The meta tag should get inserted in the `<head>` section of a website. Regardless if you are using a `header.php` and `footer.php` or not, you should have a `<head>` section in your document. For example the code in your document should be something like: <!DOCTYPE html> <html <?php language_attributes(); ?>> <head> <meta charset="<?php bloginfo( 'charset' ); ?>"> <meta name="viewport" content="width=device-width, initial-scale=1"> Also make sure you are using `<?php wp_head(); ?>` (before closing `</head>` section) and `<?php wp_footer(); ?>` (before closing `</body>` section) in your theme, as nearly all plugins depend on these. As this codes are default in the `header.php` and `footer.php` files. I guess that is no real WP question it just seems about the meta tag and section.
stackexchange-wordpress
{ "answer_score": 2, "question_score": 2, "tags": "theme development, responsive" }
Add hero image to home page (blog format) via the dashboard I am looking to add a hero image to my site's home page (blog format) **via the dashboard**. I have successfully used Advanced Custom Fields (ACF) to add hero images to static pages and posts. However I've been unable to figure out how to add a custom field to the home page when it is in 'recent posts' mode as the dashboard provides no control over the home page when it is in this mode (as far as I understand). A solution using ACF would be appreciated but is non-essential.
There are a lot of variables to this question so bear with me as I give you a solution that will get you close. assuming the field is called myimage and you're returning the image url in the field control... open your home.php file in your child them (if you don't have a child theme, make one and copy the home.php from the main theme. Then in the home.php that is in your child theme put this code: <?php if( get_field('myfield') ): ?> <img src="<?php the_field('myfield'); ?>" /> <?php endif; ?> where ever you want it to appear on the homepage. If you want the hero to be in the header you may need to use the header.php and use this code. <?php if ( is_home() ) { // This is the blog posts index if( get_field('myfield') ): ?> <img src="<?php the_field('myfield'); ?>" /> <?php endif; } else { // This is not the blog posts index } ?>
stackexchange-wordpress
{ "answer_score": 1, "question_score": 0, "tags": "posts, advanced custom fields, homepage, recent posts" }
Redirect to page for KPI/marketing purpouses I have a website with several articles and optimized seo urls. I want to add an url reference to those articles from a paper source. 1) i need a new url pointing to that articles, so I can see from the analytics how many people go to the online blog post from the paper source 2) I need to be able to shorten the url that will go to paper without altering the original post url Example: original url with content: www.mysite.web/original-content-url-too-long-to-write-on-paper paper url: www.mysite.web/gohere1 When i go to www.mysite.web/gohere1 i want to get redirected to www.mysite.web/original-content-url-too-long-to-write-on-paper How can I accomplish this? it is good to use 301 redirect? I'm not sure of it. There is any plugin that can help me to do this? Is the redirection plugin good for what I need to do?
Yes, you should use 301 redirects. There are quite a number of plugins that will do this. I would suggest trying a handful of different redirect plugins and seeing which one works best for your case. The main differences are that some will automatically include "/go/" at the beginning of the URL just to make sure you don't have conflicts with actual URLs, and some appear in different wp-admin menus, so if you have multiple site users you may prefer one plugin that appears in a certain place to either enable more users to set them up, or less users if you want to restrict who has accesss. In any of these plugins, you type in the short URL which you'll be printing, then put in the long URL which includes the full permalink plus GA UTM parameters, which you can either just type in or use Google's Campaign URL Builder to generate. The plugin will handle redirecting from the short print version to the longer query-string version which is what will feed the data into Google Analytics.
stackexchange-wordpress
{ "answer_score": 2, "question_score": 0, "tags": "redirect" }
How many posts does the loop return? I am creating a child theme archive template. I don't know how many posts will be displayed, which is fine except that i want to have a dividing line after each post except the last one. I am using the usual loop, have added a `$loopcount` variable, and then an include to create the formatting/display and add the `<div class="divider"></div>`: while ( have_posts() ) : the_post(); $loopCount++; include(locate_template('template-parts/content-newsandevents.php')); endwhile; I have looked in the codex but I can't find a way to know how many posts the loop is going to do in advance. (I could use jQ to do this, but it would be neater to do it with php I think)
Try reversing the logic, put the dividing line before the post but only do it after the first post. To answer your question though, you can get the loop count with the following: global $wp_query; $count = count( $wp_query->posts ); // or $count = $wp_query->post_count;
stackexchange-wordpress
{ "answer_score": 2, "question_score": 0, "tags": "posts, loop" }
Why WordPress does not Use Separate Table for Post Types (When Registring)? As I understand when we **REGISTER** (I am not talking about creating custom post types) custom post type WordPress not saved it in database. It is just a code. Why WordPress does not save it on separate table? Why WordPress does not Use separate table for register the custom post types? Table name : wp_post_types Columns : ID, Post Type (Ex : Posts, Pages, etc and custom post types) and many columns for other fields like slug, etc. So WordPress can store `post_type_id` in `post_type`column of `wp_posts` table instead of post type name.
It would be a challenge to hunt down a specific moment in time when that particular decision had been made. My educated guess would be that storing CPT definitions persistently would complicate how they interact with rest of APIs (especially Rewrite and localization). WP is also relatively conservative with database structure. CPT are relatively young and still evolving API, it would be a mess to try and have database table keep up with all developments of its arguments.
stackexchange-wordpress
{ "answer_score": 1, "question_score": -3, "tags": "custom post types, database" }
Sort list of page templates a-z? In the code below, it possible to sort the results alphabetically - and if so what changes do I need? <?php $templates = get_page_templates(); foreach ( $templates as $template_name => $template_filename ) { echo "$template_name ($template_filename)<br />"; } ?> If that code can't be adapted, what's an alternative query?
You can use `ksort()` function to sort the array of `$templates = get_page_templates();`. So the full code will be- <?php $templates = get_page_templates(); // Sort based on key ksort($templates); foreach ( $templates as $template_name => $template_filename ) { echo "$template_name ($template_filename)<br />"; } ?> Also see `asort()` if you need.
stackexchange-wordpress
{ "answer_score": 1, "question_score": 1, "tags": "template tags" }
set a parent category in a product woocommerce I use this function to set a new category wp_set_object_terms($product_id, $data[1], 'product_cat'); but I'd like to add a parent at this category... how could I do?
If you already got term object at `$data[1]` then you can simply access the parent by doing this- $parent_id = $data[1]->parent; If you got only term ID then you need to do- $term = get_term($data[1], 'product_cat'); $parent_id = $term->parent; After getting the parent term ID you can simply assign the product to the parent ID by doing- wp_set_object_terms($product_id, $parent_id, 'product_cat', true); **_Update: Now your previous category data will not be replaced._** Hope that helps.
stackexchange-wordpress
{ "answer_score": 0, "question_score": 0, "tags": "categories, woocommerce offtopic" }
How to display next and prev pagination links with WP_User_Query? Looking through the pagination functions available in WordPress, most seem to be associated with _posts_. paginate_links() seems to be the only function which will work with `WP_User_Query`. However, when I use that I get numbered pagination: echo paginate_links( array( 'base' => get_pagenum_link( 1 ) . '%_%', 'current' => max( 1, get_query_var( 'paged' ) ), 'format' => 'page/%#%/', 'prev_next' => true, 'total' => intval( $wp_user_query->total_users / $number ) + 1 ) ); How can I output "Prev" and "Next" pagination links that work with `WP_User_Query`? Note, I don't want to output numbered links such as 1, 2, 3 and so on.
I'm not aware of any generic helper - all the post-related navigation functions seem to be tied into the global `WP_Query` instance. The only real useful function at your disposal is `get_pagenum_link`: $paged = max( 1, get_query_var( 'paged' ) ); if ( $number * $paged < $wp_user_query->total_users ) { printf( '<a href="%s">Next</a>', get_pagenum_link( $paged + 1 ) ); } if ( $paged > 1 ) { printf( '<a href="%s">Back</a>', get_pagenum_link( $paged - 1 ) ); } Note the function returns escaped strings by default, so no need for `esc_url`.
stackexchange-wordpress
{ "answer_score": 3, "question_score": 2, "tags": "pagination, wp user query" }
How do I network enable a plugin for a multisite install via the database? The title pretty much sums up the question I have. If you want background then read on. My multisite install uses an AD integration plugin to log people on. I just upgraded PHP to the latest version but the plugin that I was using is not compatible. It's actually no longer being supported. I found another plugin to take it's place but since the install is set up to us AD integration, I'm not able to log into the dashboard because I deleted the old plugin. So I'm trying to activate the new plugin to see if it will allow me to login. I found the active plugins for the main site in the wp_options table but I need to find the active ones for my network. Can anyone help?
Hello you can query your database. e.g. SELECT * FROM **wp1_** options WHERE option_name = 'active_plugins' wp_1 your First Database in the network, then you can see the active Plugins in these site!
stackexchange-wordpress
{ "answer_score": 0, "question_score": 1, "tags": "plugins, database" }
Debugging Technique Question re: functions.php I needed to develop a technique to delete some data from the database. The technique will be part of a plugin at some point. For immediate results, I was editing functions.php on my local dev site, placing the necessary commands at the bottom of the file and reloading the page upon saving. Is this considered bad form? If so, what's the recommended method for running small bits of test code as described? Fwiw, here is a link to the code in question: <
There isn't really a prescribed way to do this, but it's probably safer to hook an action like `init` to be sure everything you need is loaded, and then maybe check for some sort of flag so you can control _which_ page loads run your code. function my_test_func(){ if( isset( $_GET['do_my_test_thing'] ) ){ // your code } } add_action( 'init', 'my_test_func' ); Then add `?do_my_test_thing=true` to the URL to explicitly run your code on that page load.
stackexchange-wordpress
{ "answer_score": 1, "question_score": 1, "tags": "plugins, functions, customization" }
Add Icon to Placeholder Text in Search Form I am trying to add an icon in the placeholder text of my search form as below but i am not getting it to work. Any ideas if this is possible to achieve? <form role="search" method="get" class="searchform group" action="<?php echo home_url( '/' ); ?>"> <input required type="search" class="search-field" minlength="3" maxlength="50" placeholder="<?php echo esc_attr_x( '<i class="x-icon x-icon-angle-right" data-x-icon="" aria-hidden="true"></i>Search', 'placeholder' ) ?>" value="<?php echo get_search_query() ?>" name="s" title="<?php echo esc_attr_x( 'Search...', 'label' ) ?>" /><button type="submit" class="search-submit">[x_icon type="search"]</button></form>
If you're using `FontAwesome`, you can display an icon in the placeholder text like this : HTML <input placeholder="&#xf0e0;" class="fontAwesome"> CSS .fontAwesome{ font-family: 'Helvetica', FontAwesome, sans-serif; }
stackexchange-wordpress
{ "answer_score": 3, "question_score": 0, "tags": "search, fonts" }
Get page ID outside the loop, matching menu ID How can I get the ID of the current post/page/category in a way that matches the ID I get from menus using `get_post_meta( $item->ID )['_menu_item_object_id'][0]`? I intend to use it in a JavaScript function. * For pages, including the Posts Page, it is the page ID * For categories, it is the category ID I have tried using `global $wp_query; echo $wp_query->post->ID;`, but it gives the ID of a post for category pages and the Posts Page. (first or last displayed post, depending on whether it is before or after the loop) More info: I add the last modified date and ID to menu items as data attributes from this question and want to save the last visit date to localstorage, keyed with the ID from the menu so I can compare them.
Use `get_queried_object_id()` to get the ID regardless of what type of object it is- term, post, page. There is also the `get_queried_object()` function, which will give you more details, but will have some structural differences depending on object type.
stackexchange-wordpress
{ "answer_score": 2, "question_score": 1, "tags": "customization, themes" }
Wordpress Drop down category as array for using in page builder I need wordpress category as drop down . So far my code function cat_drop_down(){ $categories_array = array(); $categories = get_categories(); foreach( $categories as $category ){ $categories_array[] = $category->term_id; } return $categories_array; } This renders drop down perfectly but its not passing the category id . Its rendering html like this <select data-setting="tab_title"> <option value="0">2</option> <option value="1">14</option> <option value="2">1</option> </select> So I am only getting 0,1,2 values instead of 2,14,1 that category id's. What am I doing wrong?
You are partially correct , you are not passing cat id in your parameter. Try $categories_array[ $category->term_id ] = $category->name; Now you will get category id as drop down value.
stackexchange-wordpress
{ "answer_score": 2, "question_score": 0, "tags": "categories, theme options, api" }
Why wordpress can't display the bash command properly? Wordpress version:4.7.5. test1 contain only one bash command before publlish. sort -k2,2 -k1,1 < people.txt It display as below. ![enter image description here]( test2 contain tha same bash command before publlish,just write `< people.txt` as `<people.txt`,no blank between `<` and `p`. `sort -k2,2 -k1,1 <people.txt` It display as below. Maybe it is a bug for wordpress? ![enter image description here](
When a post gets published, it runs `the_content()` through a filter to strip out unsafe HTML. It looks like the parser thinks `<people.txt` is malformed HTML and strips it out. Change `<` to `&lt;`, which is the HTML entity for `<`, and you should be able to publish the post and view it properly on the front end.
stackexchange-wordpress
{ "answer_score": 2, "question_score": -1, "tags": "html" }
.htaccess redirect for old subfolder installation to new subfolder installation and https Our old WP website: < Our new WP website: < We want to make sure that no matter what page they land on, on the old site, will redirect them to the HOME PAGE of the NEW site. Notice both sites are installed in sub-folders of the main domain name and the whole domain name has a secure certificate. Thanks.
This probably should have been asked on stackoverflow as its not wordpress specific. However, what youre looking for is a wildcard. You can find information about using them to do what you need here htaccess wildcards
stackexchange-wordpress
{ "answer_score": 0, "question_score": 0, "tags": "redirect, htaccess" }
get wordpress post loop by meta box date hello i just added date input by using metabox but i can't sort the loop in the front end page by latest metabox input date i try this $args = array( 'post_type' => 'post', 'meta_key' => 'meta_date', 'meta_value_num' => , ); query_posts($guide); if(have_posts()){ while(have_posts()) : the_post(); echo get_the_title(); endwhile; } but doesn't work for me , is there anyway to do that by using loop,thanks
Have you tried passing in the $args variable to query_posts, rather than $guide? query_posts($args); Also, you should be looking to create the custom query using WP_Query class and not the query_posts. See this answer for more details (< Try the below code: $args = array('post_type' => 'post', 'meta_key' => 'meta_date', 'meta_value_num' => , ); $my_query = new WP_Query( $args ); if($my_query->have_posts() { while($my_query->have_posts()) : $my_query->the_post(); echo get_the_title(); endwhile; } Also, please see the following: Order custom posts by a date metabox.
stackexchange-wordpress
{ "answer_score": 0, "question_score": 0, "tags": "custom field, loop, metabox" }
How to include all files within a folder to functions.php? My functions.php includes other function files located within a 'functions' directory. Currently they're individually added, in the format of this example: include('functions/login.php'); How can I modify this to include all files within the 'functions' directory, without listing them individually?
You can include/require all *.php files recursively using following function. foreach(glob(get_template_directory() . "/*.php") as $file){ require $file; } Alternatively You can use following function as-well. $Directory = new RecursiveDirectoryIterator(get_template_directory().'functions/'); $Iterator = new RecursiveIteratorIterator($Directory); $Regex = new RegexIterator($Iterator, '/^.+\.php$/i', RecursiveRegexIterator::GET_MATCH); foreach($Regex as $yourfiles) { include $yourfiles->getPathname(); } P.S Got the solution From Here.
stackexchange-wordpress
{ "answer_score": 5, "question_score": 1, "tags": "functions" }
Post editor doesn't save embed media I'm facing weird problem - I'm trying to save embed media to post in different computers and it doesn't work in all of them. We do the same process (insert -> media -> embed -> youtube code), and in one computer it work and in the other it doesn't. I've no idea what do, what can cause this weird problem?
The problem was permissions to Administrator and Editor of editing `HTML`. In multisite those permissions are gone - so I've installed `Unfilterd MU` plugin and its solved.
stackexchange-wordpress
{ "answer_score": 0, "question_score": 0, "tags": "save post, embed, post editor, youtube" }
How to override the Parent theme Function into child themes functions.php I want to know if I can override a function which is present into the parent theme function. If I redeclare the function into the child theme I am getting function already exist error. So Please guide me how can I define the function with same name in my child theme's functions.php
Check the parent theme's `functions.php`. If properly written to support child themes, each of these functions should be wrapped in a conditional as follows: if ( ! function_exists( 'theme_setup' ) ) : function theme_setup() { // Parent Theme Setup Function Code } endif; add_action( 'after_theme_setup', 'theme_setup' ); What this does is when the parent theme's `functions.php` loads after your child theme, it will first check and see if your child theme already declared the function. If it has not, then it will go ahead and define it. Otherwise it will skip the function declaration and move on. Just remember if you have to manually put these wrappers in, an update to the parent theme will overwrite them.
stackexchange-wordpress
{ "answer_score": 0, "question_score": 0, "tags": "child theme" }
How to remove menus items from Menu section from WordPress theme customizer I need to remove menu items from the menu section in the Wordpress theme customizer. Below are the screen shots: ![enter image description here]( I have tried many things, but they didn't work. I just need to remove menu items from the menu. function remove_unnessory_item_customizer($wp_customize) { $wp_customize->remove_section("themes"); /// $wp_customize->remove_section("available-menu-items"); // $wp_customize->remove_section("content"); // $wp_customize->remove_panel("nav_menus"); $wp_customize->remove_section( 'static_front_page' ); } add_action('customize_register', 'remove_unnessory_item_customizer', 9999);
Finally I was able to solve the above after researching on the net. Here I have removed the menu items by unregistering the content type. function remove_post_types() { global $wp_post_types; if ( isset( $wp_post_types[ 'post' ] ) ) { unset( $wp_post_types[ 'post' ] ); unset( $wp_post_types[ 'post' ] ); return true; } return false; } add_action('init', 'remove_post_types');
stackexchange-wordpress
{ "answer_score": 1, "question_score": 0, "tags": "plugins, plugin development" }
Can I use require() function in a template file? In my template file I want to include a library. I uploaded the library into my theme folder, and inside my theme folder is my custom template file. In my custom template file I have `require 'OAuth2/Client.php';` but when I load a page that uses the template, it gives me this: > Warning: require(OAuth2/Client.php): failed to open stream: No such file or directory in /home/healthf0/public_html/wp-content/themes/healthfitcorpwell/single-iframe.php on line 4 Obviously the file does exist, I can see it sitting there via FTP. Why is it telling me this?
You are seeing this error because you are `require`ing the file with a relative path. As @Mark Kapulun pointed out in the comments you should not use relative paths when `require`ing files. Instead you want to be explicit and use absolute paths. Use get_template_directory() which returns the > Absolute path to the directory of the current theme (without the trailing slash) In your template file the require statement will look like: `require( get_template_directory() . '/path/from/theme/root/to/file.php');` Or `get_stylesheet_directory()` if you are making a child theme. doc **Update:** As @Jack Johansson noted in his answer, you may also consider using `require_once` instead. This will protect you from errors generated by multiple inclusions of the file. See this answer for more details.
stackexchange-wordpress
{ "answer_score": 5, "question_score": 2, "tags": "functions, templates" }
Wordpress adding a menu page when activating a plugin Im making a custom plugin for wordpress and i need to create a page in the admin menu. I already have a file called mailing_list.php with the following code: function jps_mail_list_page_entry() { add_menu_page( __('JPS Mailing List'), 'JPS Mailing List', 'manage_options', 'jpsNews_mailinglist', 'jpsNews_mailing_list', 'dashicons-email' ); } add_action('admin_menu', 'jps_mail_list_page_entry'); function jpsNews_mailing_list() { echo 'hello'; } Now, in the plugin page i have this: function jpsNews_activate_plugin() { include_once(plugin_dir_path(__FILE__).'pages/mailing-list.php'); } register_activation_hook(__FILE__,'jpsNews_activate_plugin'); Its not working so, is it even possible to do it like this? how can i do it? thanks in advance.
found the problem. Turns out the function that creates the pages needs to be outside the activation hook. moved it to the end of the script and works perfectly. Thanks =)
stackexchange-wordpress
{ "answer_score": 0, "question_score": 1, "tags": "plugins, php" }
Theme Check errors about missing CSS rules REQUIRED: .wp-caption css class is needed in your theme css. REQUIRED: .wp-caption-text css class is needed in your theme css. REQUIRED: .sticky css class is needed in your theme css. REQUIRED: .screen-reader-text css class is needed in your theme css. See See: the Codex for an example implementation. REQUIRED: .gallery-caption css class is needed in your theme css. REQUIRED: .alignright css class is needed in your theme css. REQUIRED: .alignleft css class is needed in your theme css. REQUIRED: .aligncenter css class is needed in your theme css. I am getting the above error when I am running the theme-check plugin, but the problem is that I don't have any use of these classes in my theme. what should I do? Just use them for the sake of only getting rid of errors? Please guide me.
The theme check plugin checks your theme also for any default class that is generated by WordPress itself. Take a look into codex for some more info. All you have to do, is to cover these classes in your CSS file, for example: .alignleft { text-align:left } This will remove the errors from theme checker plugin.
stackexchange-wordpress
{ "answer_score": 3, "question_score": 1, "tags": "css, errors" }
Get excerpt from $post->post_content I am modifying the output of a plugin using a filter, and the $post variable is available to me, so I can display the post content like so: <h3><?php echo $post->post_title; ?></h3> <?php echo apply_filters( 'the_excerpt', $post->post_excerpt ); ?> However, the above only displays the excerpt if content has been entered into the excerpt field. It doesn't show a truncated version of the content like it would if you were able to use "the_excerpt" or "get_the_excerpt". I've also tried: <?php echo apply_filters( 'the_excerpt', $post->post_content ); ?> But that just gets the full content of the post. And I tried this: <?php echo apply_filters('the_excerpt', get_post_field('post_excerpt', $post-ID)); ?> But that returns nothing. Is there a way to get the excerpt from the full content from $post when I can't use the_excerpt or get_the_excerpt? Thank you!
When in the loop, this will produce excerpt from `$post->post_content` directly: <?php echo wp_trim_excerpt(); ?> Read more HERE. ## Alternative Solution: **If you are not in the loop** , then, you may use similar implementation as done in the `wp_trim_excerpt` function: $text = strip_shortcodes( $post->post_content ); $text = apply_filters( 'the_content', $text ); $text = str_replace(']]>', ']]&gt;', $text); $excerpt_length = apply_filters( 'excerpt_length', 55 ); $excerpt_more = apply_filters( 'excerpt_more', ' ' . '[&hellip;]' ); $text = wp_trim_words( $text, $excerpt_length, $excerpt_more ); echo $text;
stackexchange-wordpress
{ "answer_score": 10, "question_score": 5, "tags": "filters, excerpt, the content" }
I am adding a new class to my body tag if the logged in user is subscriber, need help Here's what I am doing right now. In my header.php file: <?php if ( current_user_can( 'subscriber' ) ){ textdomain_body_classes(); } else { relax(); } ?> In my functions.php class: function textdomain_body_classes( $classes ) { $classes[] = 'class-name'; return $classes; } add_filter( 'body_class', 'textdomain_body_classes' ); function relax() { } I am getting the class, class-name in my body tag when I login as admin as well as when I login with subscriber. Please advice. Thanks.
Please try this code instead- add_filter( 'body_class', 'wpse_268176_body_class' ); function wpse_268176_body_class( $classes ) { $user = wp_get_current_user(); if ( in_array( 'subscriber', $user->roles ) ) { $classes[] = 'class-name'; // your custom class name } return $classes; } Place this in your active theme's `functions.php` file. [Thanks Dave Romsey for your suggestion.]
stackexchange-wordpress
{ "answer_score": 2, "question_score": 2, "tags": "user roles, body class" }
Problems in updating a self-developed plugin I have problems in publishing the new version of a plugin I published first 5 months ago. Here is what I have done: * Developed the new functionality, tested all locally (by uploading the generated zip file from the root folder) * Copied the whole content to the trunk folder of the Wordpress plugin Subversion directory (checkout location on my computer). * Committed all content (new and changed) to the trunk. * Created a new tag by using `svn copy trunk tags/0.9.5` and committed that as well. I can now see on the plugin website that the new version is available, so the README changes have an effect. However, when I download the zip file, it has the old content. And when I install the plugin from the plugin registry, it tells me afterwards that I have installed version 0.9.4, and a new version is available. What am I doing wrong here? Here are the public resources to the case: * My plugin: < * SVN directory: <
I could solve the problem myself. Here are the resources that help in finding the (my) fault: * Wordpress@Stackoverflow: Update Plugin Detailed description, that explained the same as above in my workflow. * Expanded version of the above * Wordpress Documentation: Header information in readme.txt This was the final point. I had in my `readme.txt` in the header: Stable tag: /trunk (which possibly never worked correct). I have changed that to Stable tag: 0.9.5 I now see on < the download button with the link < which shows me that the version is now available. So the summary is: Use real version numbers in your readme.txt file!
stackexchange-wordpress
{ "answer_score": 1, "question_score": -2, "tags": "publish, svn" }
ACF add custom fields to categories and display Trying to display custom fields for categories on a category page. 1. I added the fields to ACF in the category taxonomy 2. Added this snippet into my custom category category-emails.php $image = get_field('header_image', 'category_74'); echo($image); This works. It renders out the data I have in 'header_image'. The problem is, `category_74` is hardcoded into the template. So it will only show that header_image for category_74. Trying to make it so any category or sub category of category 74 has field 'header_image' available and that I wont have to modify the template. Is there a way to write something more general, that replaces 'category_74' with something like 'categories'... I tried categories but didn't work.
Check this page out from the ACF docs: < Specifically this section: "Finding the term related to the current post" <?php // load all 'category' terms for the post $terms = get_the_terms( get_the_ID(), 'category'); // we will use the first term to load ACF data from if( !empty($terms) ) { $term = array_pop($terms); $custom_field = get_field('header_image', $term ); // do something with $custom_field } ?> I changed their "category_image" to your "header_image" value. I _think_ that should work for you.
stackexchange-wordpress
{ "answer_score": 6, "question_score": 0, "tags": "categories, advanced custom fields" }
How can I hide posts that are over 2 years old I want to apply a rule to my site that filters out all blog posts that are over 2 years old. I see some solutions that involve manually putting posts into a category and hiding the category but I want a solution that is fully automated. Is there a way to tell WP that whenever you grab posts to apply this rule: if( !is_admin() ) { select posts where post date > two-years-ago-today } Thanks
You can use the `pre_get_posts` hook to modify the main query: add_action( 'pre_get_posts', 'filter_old_posts' ); function filter_old_posts($query){ if( !is_admin() && $query->is_main_query()){ add_filter('posts_where', $callback = function( $where = ''){ $where .= " AND post_date > '" . date('Y-m-d', strtotime('-2 years')) . "'"; return $where; }); add_filter('getarchives_where', $callback ); } } This will filter the main query posts to return posts newer than 2 years old. There is also a second copy of the filter that uses `getarchives_where` to filter the archive widget results.
stackexchange-wordpress
{ "answer_score": 4, "question_score": 2, "tags": "wp query, date" }
display menu as table layout I want the menu of this site to look like the menu of this site. It's clear that they use display table and table cell but not sure how to implement it, been playing with css for a while, couldn't nail it. Didn't found a plugin that does the job but css should do. Do I have to create a custom menu layout? I think not. I'm using a wordpress menu with this plugin, and the header.php <?php wp_nav_menu( array( 'theme_location' => 'primary', 'menu_id' => 'menu-header', 'fallback_cb' => false, 'container' => false ) ); ?> <a href="<?php echo esc_url( CP_ADD_NEW_URL ); ?>" class="obtn btn_orange"><?php _e( 'Post an Ad', APP_TD ); ?></a> <div class="clr"></div>
Editing my answer. See the screenshot, if it's close enough to what you're looking for, try adding the following to your stylesheet. ![adjusted your styles via firefox element inspector]( .header_menu_res ul li { margin: 0 0 20px; width: 25%; } .menu-item i._mi, .menu-item img._mi { display: block; float: left; } .menu-item span { margin-top: 8px; display: block; margin-left: 60px; }
stackexchange-wordpress
{ "answer_score": 2, "question_score": 0, "tags": "menus, css, navigation, table" }
Programatically changing post's permalink when identical post type is published Is there a way in Wordpress for me to create content for a specific permalink ( mysite.com/current-issue ) that can be updated each month. With each update, the old content's permalink is automatically shifted to a new permalink, mysite.com/previous-issues// ? At this point, I'm not asking for detailed "how to," just a general approach. Thanks.
Yes. By default, WordPress will present the posts in order of newest to oldest so that part is already covered unless you've changed that behavior with a custom query. In order to do this, you will need to create a new rewrite rule using the `add_rewrite_rule()` function that points `/current-issue/` to the first post of that category/post type/taxonomy/etc that you are using to designate these posts. The resulting page should show only 1 post and have no reference to `wp_link_pages()` in the template file/part. As for creating `/previous-issues/`, it will be the same principal but you'll need a custom query with an offset of `1` in order to skip the first post. Edit: One thing I forgot to add - after you add these rule you will need to flush the rewrite rules. This can be done simply by going to **Settings -> Permalinks** and simply saving them without making changes.
stackexchange-wordpress
{ "answer_score": 1, "question_score": 1, "tags": "permalinks, archives" }
Add a unique class to HTML tag/element I know there is a body_class function for WordPress. But is there one (or a way) to add a class to the HTML element? My goal is to be able to add a unique class (or ID) to a page's HTML element. Currently my theme is adding the page-id-XXXX class to the body element, but I need a way to have a unique class or ID on the actual HTML element. I'd probably be fine having the page-id-XXXX also added onto the HTML element, although I'd prefer being able to have a custom field that's added to each page, where I can type in the class/ID that would then get added to the HTML element. At the very least, is there a function I can use to add a class or ID to the HTML element, similar to how the body_class function works?
Thanks to the help of this answer, I've found this solution works for adding an `id`. Though I'm not sure about adding to the `class` attribute. function add_id_to_html_element( $output ) { global $post; $output .= ' id="custom-id-' . $post->ID . '"'; return $output; } add_filter( 'language_attributes', 'add_id_to_html_element' );
stackexchange-wordpress
{ "answer_score": 0, "question_score": 0, "tags": "functions, tags, html, body class" }
get_theme_mod() only working when the customizer is open I'm using the Customizer API to enable/disable different sections of a website. When I have the customizer window open it seems that `get_theme_mod()` is returning a value ok. However as soon as I **save** and **close** the customizer window, `get_theme_mod()` does not return anything. I've seen some other questions about using `type="option"` and `get_option()` but I want to see if I can get this to work. My settings look like this: $wp_customize->add_setting( 'my_banner_setting', array( 'default' => '1', 'sanitize_callback' => 'my_sanitize_checkbox', ) ); And then I get them like this: if ( get_theme_mod( 'my_banner_setting' ) == 1 ) { get_template_part( 'sections/banner' ); } Is there something I'm missing?
Looks like I was able to fix it by adding a default value at the end of `get_theme_mod()` if ( get_theme_mod('my_banner_setting', 1) == 1 ) { // proceed } Not sure if there's another solution but this fixed it. **update** Looks like it was actually because my "1" was in quotes, removing the quote worked and I didn't have to declare the default in `get_theme_mod()` again. $wp_customize->add_setting( 'my_banner_setting', array( 'default' => 1, 'sanitize_callback' => 'my_sanitize_checkbox', ) );
stackexchange-wordpress
{ "answer_score": 2, "question_score": 1, "tags": "theme customizer, get theme mod" }
How does WordPress determine if a paged query var is too high? Inspecting the rewrite rules for author archives I can see that any digit used after page/ is matched. author/([^/]+)/page/?([0-9]{1,})/?$ => index.php?author_name=$matches[1]&paged=$matches[2] In theory, this means the following pages are possible * author/username/page/262/ * author/username/page/26278/ * author/username/page/26278292/ In real life if you visit these pages you'll get a 404 (unless the author has been crazy busy posting). How does WordPress determine if the value of the `paged` query var is too high and in such cases set the 404?
A query either returns posts or it doesn't. Whether it's a non-existent page number, a non-existent category name, a non-existent post name, etc., it's all the same. The rewrite rules is matched, which populates the query vars, which forms the query. The query is sent to the database, and the database returns some amount of posts between zero and whatever number was requested. The only difference between all of those cases is what it does _after_ it's determined to be a 404, which depends on what rewrite rule was matched. In the case that the `name` query var is populated, it tries to find the closest match with an additional `LIKE` query, and redirects there if something is found.
stackexchange-wordpress
{ "answer_score": 2, "question_score": 1, "tags": "url rewriting, query" }
How do I change Administrator to Super Administrator How does one change an Administrator to Super Administrator in cpanel for a Wordpress site? I have gone into the databases and into wp-users, wp-usermeta, but still cannot figure out how it's done. Context - a PHP developer who worked on the site changed the Super admin to Administrator and I need to set the person back to Super. Any input is appreciated. Thank you.
What RST said. "SuperAdmins" are for network (multi-site) only. That user has ability to be the admin of all sub-sites. "Admin" is the highest level for non-multi-site (non-network) sites. (added as an answer to show that this question is answered by a comment to the question).
stackexchange-wordpress
{ "answer_score": 3, "question_score": 1, "tags": "admin" }
How can I use default CPT templates from sub-folder? Is it possible to move 'default' CPT templates (example: single-cpt_name) to a sub-folder and still have WP recognise and auto-assign them? If so, how?
I think you should use `single_template` filter hook to load your template from a subdirectory. The full code will be like below- function the_dramatist_get_custom_post_type_template($single_template) { global $post; if ($post->post_type == 'your_post_type') { // Your post type directory with the post type template file name $single_template = dirname( __FILE__ ) . '/post-type-template.php'; } return $single_template; } add_filter( 'single_template', 'the_dramatist_get_custom_post_type_template' ); Please read the documentation for further information. Hope that helps.
stackexchange-wordpress
{ "answer_score": 2, "question_score": 0, "tags": "templates" }
Restrict Search Query To After Specific Date This code is not working add_filter( 'pre_get_posts', 'search_filter' ); function search_filter($query) { if ( ! is_admin() && $query->is_main_query() ) { if ($query->is_search) { $query->set( array( 'date_query' => array( array( 'after' => 'January 1st, 2013', 'inclusive' => true, ) ) ) ); } } } I want to remove all results prior to jan 1 2013 so only posts after the 1/1/2013 will be shown in the results.
Note this problematic line: $query->set( array( 'date_query' => array( it should be $query->set( 'date_query', array( So try instead this form: $query->set( 'date_query', [ [ 'after' => 'January 1st, 2013', 'inclusive' => true, ] ] );
stackexchange-wordpress
{ "answer_score": 2, "question_score": 1, "tags": "pre get posts" }
Integrating non-WooCommerce and WooCommerce Orders together What we are trying to achieve is a seamless integration with order/transaction data that has come from a legacy system, and without turning them into actual WooCommerce orders and inserting them into WooCommerce (theres 800k so far..). When a customer is looking through their list of orders, they shouldn't see a different in the look of the non-WooCommerce (pre-WooCommerce) orders and WooCommerce orders (which are just posts within the system). We want this data stored separately for various reasons, i.e. tables storing the historical data. We're currently modifying any actions that interact with the order but are looking for a cleaner solution that would focus on extending the WC_Abstract_Order or WC_Order, **has anyone dealt with this before?**
Turns out that the new CRUD functionality added in 3.x will allow me to deal to a single point for each data type, in this case it's Orders <
stackexchange-wordpress
{ "answer_score": 1, "question_score": 1, "tags": "plugins, woocommerce offtopic, e commerce" }
How do I change/remove styling (top border) on main menu for active page and hovering (Avada Theme) As per the title, how do I change/remove styling (which is a white top border) on the main menu for both the active page and on hovering a menu item? I am using the Avada child theme and started out with the Architecture demo content. I'm new to web dev and using Custom CSS but can figure most things out with a little guidance. Have checked the forum for existing threads but nothing I have tried has works so far. Thanks in advance.
Go to you theme admin panel then Appearance > Editor. Then paste this code bellow into Stylesheet (style.css): .fusion-main-menu .current_page_item > a { border-color: #000 !important; } .fusion-main-menu > ul > li > a:hover { color: #000 !important; } Hope it solve your problem
stackexchange-wordpress
{ "answer_score": 1, "question_score": 0, "tags": "menus, child theme, css" }
Bank account number and Sort Code in a form I am creating a Finance form for a small car finance company using Wordpress. However a potential customer needs to be able to enter his bank account number and bank sort code into the form along with his name and address details. The form is then sent to the owner of the finance company. My question is what is the best way to keep this information secure. I was going to use an SSL certificate and perhaps a wordpress plugin like WP PGP, but I do not know if this would be secure and also if there are any legal problems with doing this. Any help would be greatly appreciated. Many thanks
This sounds like bad news. There are many technical and legal hurdles involved in collecting bank info online. It is easy to mess up. All SSL does is protect information in transit between a browser (person filling the form) and the server. Once it gets to the server you need to handle it properly. If you plan to use a common form plugin, the info will most likely get stored in your DB or emailed as plain text; **that's bad**. I'd be sceptical of encryption plugins as well unless they were audited, even then you may have another rouge plugin that can cause issues. I'd start by looking into the following: * Your local/national regulatory requirements * Where the bank info goes after the owner get's it. Is it a third party? Do they offer a secure API or portal you can leverage? * PCI compliance. Even though you probably don't fall into its scope they can give you an idea of how this type of information is handled
stackexchange-wordpress
{ "answer_score": 2, "question_score": -3, "tags": "security" }
Patient portal using wordpress A friend of mine has got a small vet clinic. He asked me whether is there any way to create in wordpress a kind of patient portal. While membership plugins would do most of the stuff, he is looking into one specific feature: \+ attaching PDFs / examination results to specific accounts (so him as an admin would somehow link / add files to specific accounts in which user could only download/view file) do you have an idea how to deal with that? I know that buddypress has got plenty of functions but i doubt if its possible to link (as admin) a file to person account.
Yes its possible to link a file to buddypress member as admin. An important piece of the API is the BP_Attachment class. You can extend it to be ready to receive user submitted files, validate these submissions and finally write the files in a /wp-content/uploads's subdirectory you define. You can review more details and final solution at <
stackexchange-wordpress
{ "answer_score": 2, "question_score": 0, "tags": "uploads, buddypress" }
User Wordpress menu in custom page I have a third party app installed (such as a forum) that I've linked with my Wordpress menu (as a custom link). However I wish to show the same wordpress menu above this app (I have it's source code so can make changes). What do I need to do so it shows up nicely on any page? Right now clicking on it opens the new page but naturally without the current theme. I'd love for it to maintain the same overall look if I can.
You'll need to load in the external wordpress library first, and then you can call the admin bar. // Load the external Wordpress files define( 'WP_USE_THEMES', false ); require( './wp-load.php' ); and then call `wp_head()` and `wp_footer()` accordingly to load the relevant display code.
stackexchange-wordpress
{ "answer_score": 0, "question_score": 0, "tags": "customization, menus" }
Synchronize Custom post type tags to WordPress default posts tags I am new with WordPress plugin development. I have to Synchronize custom post type tags with WordPress default post type tags. So when user will create, delete or update any custom post type tag it should be updated in Default tags. I do not have enough knowledge with WordPress hooks so if someone guide me about this that will be appreciated. This is urgent task for me to do so i have to find out the solution for this. Thank you!
You need to register the `post_tag` taxonomy for the post type. For a quick, after the fact, way to do this (meaning the CPT has already been registered, etc.), you can use `register_taxonomy_for_object_type()`. A workable example is below. Edit the value for `$object_type`, and place the example below in the _functions.php_ of your child theme: add_action( 'init', 'my_cpt_has_tags_now' ); function my_cpt_has_tags_now() { $taxonomy = "post_tag"; $object_type = "name_of_your_cpt"; register_taxonomy_for_object_type( $taxonomy, $object_type ); }
stackexchange-wordpress
{ "answer_score": 2, "question_score": 2, "tags": "plugin development, filters, hooks" }
How to source control manage site images While I'm not new to development, I am fairly new to WordPress. As I was reading up on how to best manage a WordPress site in source control, I found repeated advice to not check in `wp-content/uploads`. I understand why from the reading. At the same time, I would still like to keep my the images that I use with the site design in some place where, should the worst happen, I can easily recover the original design. Am I completely thinking about this the wrong way, or are there suggestions that I wasn't able to find via a search? P.S. For a background, I am used to standalone webapps - .NET, JavaScript, Java - where images are generally committed with the code since they are fairly static and don't change often.
Whatever is in the `wp-content/uploads` directory is not source, it is data, some of it is automatically generated. Images related to source code, like images used in CSS should "live" in the theme or plugin files. It is possible to use the likes of GIT over that directory, but the results will lack any sensible versioning information (no comments on why a file got there, not way to associate that channge with a new post being published etc) which degrade the whole thing into just a not very efficient backup system. P.S. If you are doing any change on production which needs to go into version control, then you are doing it wrong. Changes need to be tested on development or staging servers, pushed into git and only then pulled into production (git or just FTP or maybe composer, whatever works for you).
stackexchange-wordpress
{ "answer_score": 0, "question_score": 0, "tags": "images, git" }
Why does WP_Query strip colons from tag names? I'm using WP_Query to select a specific set of posts: $args = array ( 'orderby'=>'rand', 'posts_per_page' => 1, 'category_name'=>'exercise', 'tag' => 'org:abc' ); $the_query = new WP_Query( $args ); but, when I run the query, it seems to be stripping the colon (:) in the tag name, so the query (when you output it) is searching for tag='orgabc', rather than 'org:abc'. This also seems to happen with =, i.e. 'org=abc' I've had to change my taxonomy as a result, but does anyone know why the colon is being stripped? is this a special character?
The `tag` parameter should be the tag's _slug_. If you look at your tag's archive URL (the _view_ link when editing the tag), it won't have the colon in it, because that's not a legal character in a URL. Your tag's _name_ can still have the colon, and you can use the URLencoded version of a colon `%3A` in the slug if you want, though you will have to manually enter that in the slug field.
stackexchange-wordpress
{ "answer_score": 3, "question_score": 0, "tags": "taxonomy, tags" }
Including a 3rd party library in Wordpress which needs to be accessible by wp-config I'm attempting to use the Defuse encryption library in Wordpress: < I'm using this guide as a resource for how to implement it: < My question is, if my wp-config file requires access to a library, where should I put the library and require the file? Long description of problem: In the tutorial it says to generate and store an encryption key and then place it in a constant in wp-config.php. In order to do that, I would need access to the library from wp-config. I was originally planning on putting the library in a plugin and requiring it from there, but my guess would be that if I did that, I wouldn't be able to access it from wp-config. So my question is, where should I actually put the library and where should I require it if I need access to it from wp-config?
1st, the key should be generated once, not per request. The tutorial is suggesting you generate it via the library (probably via cli, or one off script you run in the browser) and then simple add: define('JOSH_ENCRYPT_KEY', 'the-random-key-you-generated-gets-copy-pasted-in-here-manually'); into your `wp-config.php` file, so you dont need the lib to be in scope at that point. If you are doing this in a plugin, you can define the constant within the plugin instead of in the `wp-config.php` file if you prefer. However, i think the tutorial has a major flaw, in that the wordpress options api handles non string values (objects, arrays etc), whilst the wrapper provided does not
stackexchange-wordpress
{ "answer_score": 2, "question_score": 2, "tags": "wp config, library" }
WP_List_Table default orderby is numeric I display a custom table using the `WP_List_Table` class. Everything works, but I want the default `orderby` to be numeric (by ID). If it is by string it works. this is the function: private function sort_data( $a, $b ) { // Set defaults $orderby = 'id'; $order = 'desc'; // If orderby is set, use this as the sort column if(!empty($_GET['orderby'])) { $orderby = $_GET['orderby']; } // If order is set use this as the order if(!empty($_GET['order'])) { $order = $_GET['order']; } $result = strcmp( $a[$orderby], $b[$orderby] ); if($order === 'asc') { return $result; } return -$result; } The outcome is as this: * 9 * 8 * 7 * 6 * 5 * 4 * 3 * 2 * 11 * 10
Try the `strnatcmp()` for "natural" ordering, instead of `strcmp()` (src) or handle the ID ordering specially, e.g. with typecasting and the spaceship operator `<=>` in PHP 7.
stackexchange-wordpress
{ "answer_score": 7, "question_score": 0, "tags": "wp list table" }
Cannot verify nonce I create nonce as $nonce = wp_create_nonce("action"); And then send the email with nonce to user. In the email there is the link to a page. In the page I form the nonce the same way and try to verify it using wp_verify_nonce($nonce, "action"); , and it doesn't work, it always fails to verify, and returns false. What am I doing wrong?
What you are doing wrong is using nonce in a context it was not intended to be used in. nonces should be used on web pages for logged in users, not just a random "it has something to do with security so it has to be right" kind of measure ;). If you need to validated the authenticity of the link you have sent, just use an md5 hash (or any other hash generator) based on whatever long term "secret" information you have on the user. At the best case, nonces "live" for 48 hours, while emails might be opened later then that.
stackexchange-wordpress
{ "answer_score": 2, "question_score": 0, "tags": "nonce" }
Drawbacks to using Options -Indexes I was wondering if there were any drawbacks to using Options -Indexes in my WordPress htaccess file to block access to directories such as uploads, etc. Wpbeginner has a post on it here
There are some legitimate use cases for enabling `Indexes` but they're probably not applicable to most sites (especially WordPress sites). For example `Indexes` are helpful on file storage mirrors where you want to provide readonly access to a subset of folders & files without having to build your own UI. As a best practice, yes, disable them globally using `Options -Indexes`.
stackexchange-wordpress
{ "answer_score": 1, "question_score": 1, "tags": "htaccess, directory" }
Sort posts in a specific way I currently have 6 posts that are under the category 'services'. Each service has the_content and 1-2 documents (Brochure and/or T&C and an external form) Now, let's assume those 6 posts have the ID 1,2,3,4,5,6 but I want it in as 2,5,3,1,4,6. Is that possible? If so, how would I be able to achieve it?
This is possible with native query parameters like this: $posts = get_posts([ 'post__in' => [2,5,3,1,4,6], 'orderby => 'post__in', ]); This combination will instruct WP to fetch specific posts by ID _and_ order them in the specific way that you supplied IDs.
stackexchange-wordpress
{ "answer_score": 1, "question_score": 0, "tags": "php, wp query" }
wp media regenerate unknown --image_size parameter It is said in the documentation that we can set the --image_size parameter to regenerate all images for only this size. However, I am getting this for this command: Error: Parameter errors: unknown --image_size parameter I am trying the following example from the documentation: wp media regenerate --image_size=large How do I regenerate images only for a specific size?
I was able to duplicate the issue when running WP-CLI version 1.1.0, but the command worked successfully when I updated to the nightly build using: wp cli update --nightly The `--image-size` parameter was added to wp-cli/media-command on April 13, 2017 after the current stable release of WP-CLI v1.1.0 on February 1, 2017. This feature is available in the nightly builds and will likely appear in a future stable release. **Update:** As of WP-CLI version 1.2.0, `wp media regenerate --image_size=large` will work right out of the box.
stackexchange-wordpress
{ "answer_score": 6, "question_score": 4, "tags": "media, wp cli" }
The MySQL Connection could not be established., before it was joomla but i have change it into worpress When i have removed all the file from the `public_html` and installed WordPress ... I got this error: > The following errors were found : > > The MySQL Connection could not be established. do i need to delete MySQL on the database when i delete the Joomla! file...?
Check that you have assigned the user/pass to the database via your cPanel. And that those credentials match what WordPress expects. Usually, the WP install process will do this for you. (I assume that you created a new WP installation, and are not trying to re-use an existing database.) Also, you should obfuscate the URL in your screenshot...you don't want to give out that confidential info to hackers who might be lurking, even though that possibility is remote. Your screenshot also shows (I think) your database credentials. Again, not good. For future questions, just copy the actual error message, watching out for PII (Personally Identifiable Information; in this case: credentials, URLs, and other stuff).
stackexchange-wordpress
{ "answer_score": 0, "question_score": 0, "tags": "database, mysql, sql" }
Upload image to wordpress using REST API I am developing API for Wordpress using REST-API. Now I am stuck at one point where I am not able to develop the API through which I can upload the image to wordpress using Rest API. I am using Postman to test API developed for my website
You can upload images just like your normal PHP/Wordpress file uploads. Reference `=>` wp_handle_upload $mimes = array( 'bmp' => 'image/bmp', 'gif' => 'image/gif', 'jpe' => 'image/jpeg', 'jpeg' => 'image/jpeg', 'jpg' => 'image/jpeg', 'png' => 'image/png', 'tif' => 'image/tiff', 'tiff' => 'image/tiff' ); $overrides = array( 'mimes' => $mimes, 'test_form' => false ); $upload = wp_handle_upload( $_FILES['YOUR_INPUT_FILE_NAME_HERE'], $overrides ); remove_filter( 'upload_dir', array($this, 'change_upload_dir') ); if ( isset( $upload['error'] ) ){ // SOME UPLOAD ERROR OCCURED } else { // File uploaded successfully. $uploadedFileURL = $upload['url']; $uploadedFileName = basename($upload['url']); } > And you can attach files in postman following way. ![enter image description here](
stackexchange-wordpress
{ "answer_score": 3, "question_score": 2, "tags": "rest api" }
How do I redirect all 404 errors of a specific post type to another URL? I have a custom post type containing job listings, that is highly volatile. Jobs are frequently added and removed. Our analytics show that a lot of crawling errors are for detail pages of jobs that have been unlisted. The solution I came up with is to redirect all visits for non-existant URLs within the CPT's slug to the job listing overview, and I would like to automate this. How would I go about this? I'm looking for a solution that does this very early and skips as much unnecessary calls as possible. (i.e. something earlier than doing this in header.php, ideally as an action) Example: * `mydomain.com/jobs/existingjob/` delivers the detail page for the job * `mydomain.com/jobs/nojobhere/` does not exist and would throw a 404 but instead gets redirected to `mydomain.com/jobs/`
It looks like `template_redirect` is as far up the WordPress action chain you can go while still being able to detect that a 404 error is being thrown. This action will trigger before any template files would be loaded so it will happen before loading unnecessary resources. You can try adding this into your `/wp-content/themes/yourtheme/functions.php` file to achieve a dynamic redirect for all 404's that happen when viewing single jobs: add_action( 'template_redirect', 'unlisted_jobs_redirect' ); function unlisted_jobs_redirect() { // check if is a 404 error, and it's on your jobs custom post type if( is_404() && is_singular('your-job-custom-post-type') ) { // then redirect to yourdomain.com/jobs/ wp_redirect( home_url( '/jobs/' ) ); exit(); } }
stackexchange-wordpress
{ "answer_score": 3, "question_score": 2, "tags": "custom post types, php, redirect, 404 error" }
Navigation menu, remove item from desktop Using theme (and child theme) of Sailent, I'm trying to work out a way to completely remove a menu item from my navigation bar while on desktop. See site here: < ![It's there, although not visible]( As you can see, the text for the menu item isn't there, yet it messes up the alignment of the menu. At the moment, I have that menu item set to a css class of mobile-only with css settings as: .mobile-only { visibility:hidden; } @media (min-width:992px) { .desktop-only { visibility:visible !important; } } @media (max-width: 991px) { .mobile-only { visibility:visible !important; } .desktop-only { visibility:hidden !important; } }
Although this is not really a WordPress question, but the `visibility` property does not actually HIDE any element. It only fades it so you can't see it, but it still reserves space for it. You need to use the `display` property: .mobile-only { display:hidden; } @media (min-width:992px) { .desktop-only { display:block !important; } } @media (max-width: 991px) { .mobile-only { display:block!important; } .desktop-only { display:hidden !important; } } You might want to change the `block` to `inline-block` or `inline`, depending on the original value of your menu's item (which is usually `inline-block`).
stackexchange-wordpress
{ "answer_score": 0, "question_score": -2, "tags": "menus, navigation, mobile, responsive" }
How to change a form end email? First I should say that am a beginner with WordPress. I am trying to change the email that a form sends the information to. However, when I go to the "Pages" section and open the "contacts" file I don't see any form details. The only thing I see is the text "Contact us now for free estimate:" and the mobile number (see the image bellow), nothing about the form. Any suggestions on how I can access the details of this form so I can change the email that it sends the data to? ![enter image description here](
In admin, check the page template used by the contact page, and look for it in your theme folder. Page templates are applied as described here: <
stackexchange-wordpress
{ "answer_score": 1, "question_score": 0, "tags": "forms" }
Password Protecting Media Is it possible to password protect a PDF for visitors to our website (not users)? We have uploaded a PDF to our media and created a link to it on a page, but we would like to password protect just that PDF and not the whole page that contains the link to it.
an additional solution that may work and require no coding is to insert the PDF into a post and just have the post protected. Then insert the post onto the page
stackexchange-wordpress
{ "answer_score": 0, "question_score": 1, "tags": "media, password, pdf" }
Why does using excerpt_more filter change link location? I added the following to my `functions.php` file in order to change the 'read more >' link that appears after `the_excerpt()` is called. add_filter( 'excerpt_more', 'edit_more_link', 11 ); function edit_more_link() { ?> <a class="read-more" href="<?php the_permalink() ?>?template=iframe">read more &raquo;</a> <?php } The problem now is that the link is appearing before the excerpt text. Without the code added, the default link appears after the excerpt, which is what I want. Why is this happening?
Filters are for modifying values before they are output. Typically the function is passed some value where you can modify it or overwrite it, then pass the result back. Your link is appearing out of place because you're outputting the value directly, change it to `return` instead. Also note that most template tags have versions that output their value, and ones that return. In your function `the_permalink` is changed to `get_permalink`. add_filter( 'excerpt_more', 'edit_more_link', 11 ); function edit_more_link() { return '<a class="read-more" href="' . get_permalink() . '?template=iframe">read more &raquo;</a>'; }
stackexchange-wordpress
{ "answer_score": 0, "question_score": -1, "tags": "filters, excerpt" }
How to send file by wp_remote_post? ## I don't want cURL in my WordPress plugin Hi, cURL is not safe to use on WordPress site. And sometime, cURL has been disable on customer hosting. ## And i decided to use wp_remote_post to send file for my plugin Here my code : $service = URL SERVICE ; $headers = array( 'accept' => 'application/json', // The API returns JSON 'content-type' => 'application/binary', // Set content type to binary ); $data = array( 'headers' => $headers, 'body' => file_get_contents($image_file), ); $response = wp_remote_post($service, $data); But on server, i cannot received file from wp_remote_post. Please help me fix this issue ? How i can config to send file from wp_remote_post same as CURLFile ?
I found an solution for this issue, i using wp_remote_post to send binary of file to server. When processing data received on server, i use this code to get data of file $file = file_get_contents('php://input'); And i write it to temp file $temp = tmpfile(); fwrite($temp, $file); $metadata = stream_get_meta_data($temp); Do you have any other solution ? Please discuss with me to find best answers.
stackexchange-wordpress
{ "answer_score": 0, "question_score": 1, "tags": "curl, wp remote post" }
Dynamically import posts from one wordpress site to another I have found some topics related to this issue but no solution... I have 2 different websites. I would like that, when I post some posts on the first one, they are automatically posted on the second one, including the featured image. I tried using a plugin called "RSS Post Importer" but it doesn't get the featured image. I did some research and found that a solution is to use fetch_feed and wp_insert_post and create a custom plugin (or function) using these two functions. Is there an easier/better way ?
I finally achieved it using the RSS Post Importer plugin. Then I used another plugin that allows to tweak the RSS feed on the first website to add the featured image in the content of the feed item. Then you just need to strip the first image from the content of the newly created post.
stackexchange-wordpress
{ "answer_score": 0, "question_score": 1, "tags": "rss, import" }
how to add rewrite rule to wordpress default post type hello trying to add rewrite rule to default post type with this add_action('init', 'add_my_rewrite'); function add_my_rewrite() { global $wp_rewrite; $wp_rewrite->add_rule('(.*)/server/([^/]+)','index.php?p=$matches[1]&server=$matches[2]','top'); $wp_rewrite->flush_rules(false); } function add_query_vars_filter($vars){ $vars[] = "server"; return $vars; } add_filter('query_vars','add_query_vars_filter'); but doesn't work let's say my post url is ` i want the url to be like that ` with adding the parameter server to the url how can i do that thanks
The `p` query var expects a post ID, use `name` instead. Also note that rules should only be flushed when they change, as it's a computationally expensive operation. It's best to do that on theme change or plugin activation, whichever is appropriate for where your code is located. You can also do this by just visiting the Settings > Permalinks page in admin. add_action('init', 'add_my_rewrite'); function add_my_rewrite() { add_rewrite_rule( '^(.*)/server/([^/]+)', 'index.php?name=$matches[1]&server=$matches[2]', 'top' ); } function add_query_vars_filter($vars){ $vars[] = "server"; return $vars; } add_filter('query_vars','add_query_vars_filter');
stackexchange-wordpress
{ "answer_score": 1, "question_score": 1, "tags": "permalinks, rewrite rules, query variable" }
Return user taxonomies I am trying to return users taxonomies which where generated from using a plugin and then registering the taxonomy in the functions file. The taxonomy generates a checkbox list in the standard user profile section to which you select the taxonomy you wish to use. I simply canot get it to output, I am fetching everything else just fine like so for example: $consultant = (get_query_var('author_name')) ? get_user_by('slug', get_query_var('author_name')) : get_userdata(get_query_var('author')); And to fetch the name I do: `echo $consultant->first_name` I have registered this taxonomy with the name of 'Skills' I have tried a number of methods but nothing seems to be outputting the array.
You can use wp_get_object_terms once you have the `$consultant`. For example: $user_terms = wp_get_object_terms( $consultant->ID, 'skills' ); Note that you can use the third argument to customize the term query.
stackexchange-wordpress
{ "answer_score": 0, "question_score": 1, "tags": "taxonomy" }
Regenerate Thumbnails I am using custom image sizes with add_image_size for custom post types. For example for books custom post type if($post_type_name == 'book'){ add_image_size('75x75',75,75, true); add_image_size('150x150',150,150, true); }elseif($post_type_name == 'music'){ add_image_size('200x200',200,200, true); add_image_size('400x400',400,400, true); } But when I regenerate thumbnails it doesn't work. Why?
`add_image_size` is intended to be defined globally (outside of the context of a post type). This is because when images are generated they are not yet attached to a specific post type. If you're using a plugin or WP CLI to regenerate the thumbnails, you are _outside_ of the context of a post type. Therefore those checks are always going to fail. You should simply do add_image_size('75x75',75,75, true); add_image_size('150x150',150,150, true); add_image_size('200x200',200,200, true); add_image_size('400x400',400,400, true); In your `functions.php`, class file, plugin, etc.
stackexchange-wordpress
{ "answer_score": 1, "question_score": 1, "tags": "custom post types" }
a:0:{} is replaced into database as s:6:"a:0:{}"; When I try to add user meta to empty array as: `a:0:{}` it's replaced into database as `s:6:"a:0:{}";` I just need to save it as I written as `a:0:{}` this is my code: $sassada = get_user_meta($current_user, 'custom_system'); if(empty($sassada)){ add_user_meta($sassada, 'custom_system', 'a:0:{}'); }
API calls are API calls, not database writes. What and how information is stored in the DB is usually best left as an unknown since, unless explicitly defined in the API, it might change. Specifically in this case, wordpress will serialize the value being passed, and since you are passing a string it is serialized as a string. And if what you are after is storing an empty array, just pass an empty array as the value.
stackexchange-wordpress
{ "answer_score": 3, "question_score": 0, "tags": "php, user meta" }
How do i get user data from a custom table in the wordpress database by user ID? I've got a few custom user data fields that require user data from a custom database table. I've tried: global $wpdb; $table_name = $wpdb->prefix . "wplusersprofiles"; $user = $wpdb->get_results( "SELECT * FROM $table_name" ); and calling the data like: <tr> <th><label for="gender"><?php _e("Gender"); ?></label></th> <td> <input type="text" name="gender" id="gender" value="<?php echo $user->gender ?>" class="regular-text" /><br /> </td> </tr> But with no success. Example table in the DB: ![enter image description here](
The first section of your code is correct global $wpdb; $table_name = $wpdb->prefix . "wplusersprofiles"; $user = $wpdb->get_results( "SELECT * FROM $table_name" ); The problem is in the way you tried to fetch the individual row data. The get_results function in your case returns an object array. So the correct way to fetch individual data should be like... <?php foreach ($user as $row){ ?> <tr> <th><label for="gender"><?php _e("Gender"); ?></label></th> <td> <input type="text" name="gender" id="gender" value="<?php echo $row->gender ?>" class="regular-text" /><br /> </td> </tr> <?php } ?>
stackexchange-wordpress
{ "answer_score": 13, "question_score": 2, "tags": "database" }
Redirect to home if page doesn't exists I would like to redirect users to my home page when the requested page or post cannot be found, but don't know how to go about with that. How do I proceed with such and action?
You can use this code inside your `404.php` template file to safely redirect to users to homepage: wp_safe_redirect(site_url()); exit(); Use this code before every line of code in your `404.php`. This will redirect everyone who visits the 404 page to the website's home URL, which would be what you are looking for. You don't have to delete the content of your `404.php` file, since every line of code after the `exit()` will be ignored.
stackexchange-wordpress
{ "answer_score": 1, "question_score": 0, "tags": "redirect, 404 error" }
get the permalink never return with empty value hello am trying to check if there's a url to the custom post type inside default post type page so i used if(get_the_permalink($customID)){ echo 'true'; }else{ echo 'false'; } it's always echo true even if the $customID not exists is there's way to do that with `get_the_permalink();` function and i know about `get_post_status()` but i need to do it with `get_the_permalink`
You just need to check if `$customID` is set, first. E.g. if ($customID && get_permalink ($customID)) { echo 'true'; } else { echo 'false'; }
stackexchange-wordpress
{ "answer_score": 1, "question_score": 0, "tags": "custom post types, permalinks" }
Timber - don't display shortcode I'm using Timber on a WordPress site but am having an issue with shortcode content appearing on the homepage as html/text. I'm using `{{ post_content|exceprt(30) }}` to display the post content but this causes shortcodes to be displayed. I'd prefer not to display any shortcode content at all on this page (either rendered or as html/text), if possible. Is there any way to filter out shortcodes using Timber?
try adding the pipe stripshortcodes `{{ post_content|exceprt(30)|stripshortcodes }}`
stackexchange-wordpress
{ "answer_score": 0, "question_score": 0, "tags": "shortcode" }
Automating Page Creation I have a huge website, with thousands of pages. It's a reference site, with a page for every country, each U.S. state, every species of mammal, etc. I've tried WordPress on some smaller sites and love it. Now I'm trying to figure out if there's a way to convert my reference site to WordPress. So here's my first question. If I replace this site with WordPress, is there some way I could automate page creation? For example, let's say I want to create 250 pages for countries and 50 pages for U.S. states. Rather than create each page one at a time, I'd like to just push a button and let WordPress instantly create 300 pages, each with a specific title, URL and channel (Nation vs State). Is there a way to do this?
Where is the content coming from? You can easily write PHP code that will create pages, but the content has to come from somewhere. If the content already exists, say in a database that you own, then you can code a process to take the data from a table/record and convert it into a post/page.
stackexchange-wordpress
{ "answer_score": 1, "question_score": 1, "tags": "automation" }
How to change WP's post editor's font I want to change font during edit post (as in picture below). I tried to find css font for that content but could not. Please help! Many thanks! ![enter image description here](
Wordpress default editor have no support for any font change option on it's tool bar. You have to do some css tricks but its not so easy if you are not a developer. Also its not a good idea to change theme functions or css. **But there have a good solution:** You can do this easily with a little but powerful plugin like This You can also check an intro video from Here Hope it will solve your problem. **Note: If you don't want to use plugin like this then you have to change core css of your theme which is not a good practice.**
stackexchange-wordpress
{ "answer_score": 0, "question_score": -1, "tags": "fonts" }
Change the last separator in the_terms How can i show `the_terms` with commas and "&" before the last one Example: Tags: books, review & history I need show a "," between the terms and a "&" before the last term. I'm using the following code to show `the_terms` in the single post: <?php the_terms( $post->ID, 'post_tag', 'Tags: ', ', ', ' ' ); ?>
$terms = get_the_term_list( $post->ID, 'post_tag', 'Tags: ', ', ', ''); echo preg_replace('/^(.+),([^,]+)$/', '$1 &$2', $terms); Explanation for /^(.+),([^,]+)$/: / - delimiter ^ - string beginning .+ - 1 or more characters [^,]+ - 1 or more characters that are not a comma $ - string end $n is the nth match i.e. nth pair of brackets
stackexchange-wordpress
{ "answer_score": 0, "question_score": 0, "tags": "terms" }
Admin area is not loading properly Recently I've locked myself out of my WordPress site by changing the site URL. I fixed that problem by reverting the site URL to the original one in PHPmyadmin database. But what happens now is that my website is working properly but whenever i access the back-end, only the HTML part of WordPress is loading and not the CSS part. Can anyone explain to me what is happening and how to fix this?
So what i did to solve this issue. I hardcoded the right url's into the wp-config.php file in which they were missing completely. Although this prohibits me from updating the site or home url through the wp interface in the future, it was the best solution for me at the time. Thank you all for replying and trying to help > Steven
stackexchange-wordpress
{ "answer_score": 0, "question_score": 0, "tags": "wp admin, css" }
edit_{$taxonomy} | Hook Hi i am not very experienced with plugin development and i am using edit_{$taxonomy} | Hook but i am not able to get new updated values using this hook. Here is my code function action_edit_taxonomy( $term_id, $t_id ){ $term = get_term($term_id); print_r($term); exit; }; add_action( "edit_um_user_tag", 'action_edit_taxonomy', 10, 6 ); But $term is returning old term saved value, not which i am going to update now. So how i will be able to get new value which i am going to update now. I will really appreciate it if someone will guide me that where i am wrong with this code. I have tried to find out help but still the problem is there. I am already using get_term() function for create_{$taxonomy} | Hook and get_term is working for it but it is not returning correct value for edit_{$taxonomy} | Hook. Thank you!!
You are getting old version of the term, because edit_{$taxonomy} action is fired after the term is updated but before term's cache is cleared. Use edited_{$taxonomy} hook, which fires your action after the term is updated and its cache is cleared.
stackexchange-wordpress
{ "answer_score": 2, "question_score": 1, "tags": "plugin development, hooks" }
remove white overlay I am trying to find a way to remove the white overlay on my pages in the website my event or artist. I tried to use inspect element to locate what created the white overlay but i was unable to locate the exact property. pages: < <
On both pages template find `<div class="overlay-for-image-bg">` and replace it with `<div>` only. Needles to say, you should make this change in child theme's template, to avoid your changes being overwritten when you update your theme. Or you can modify `/wp-content/uploads/mesh/custom.css` file by removing the following block: .overlay-for-image-bg { /* some stuff */ }
stackexchange-wordpress
{ "answer_score": 0, "question_score": -2, "tags": "css" }
Synchronize custom post type tags with WordPress default post type tags I am not very experienced developer and i have to solve one issue. My client wants to synchronize Ultimate member plugin tags (custom post type tags) with WordPress default posts tags. Actually ultimate member plugin tags and default posts tags will be same and he do not want to create these again. So he wants to use same taxonomy for both of these posts types (default and custom). So according to my view if i will be able to use ultimate member plugin tags for default posts tags then all of my problem will be solved. So in this way default posts will ignore there own tags and instead of this will use ultimate member plugin tags as a taxonomy. I am not sure that my idea is right or not but if someone will be able to guide me about this, i will really appreciate it. Thank you!!
`register_taxonomy_for_object_type()` will do what you want as long as the taxonomy and object (`post_type`) are already registered elsewhere. Very useful when dealing with a plugin's CPTs you need to add a taxonomy to. add_action( 'init', 'add_tag_tax_to_posts'); function add_tag_tax_to_posts(){ register_taxonomy_for_object_type( 'SLUG_OF_PLUGIN_TAG_TAX_HERE', 'post' ); } Or to do the reverse, and add the default tags (`post_tag`) to the CPTs: `register_taxonomy_for_object_type( 'post_tag', 'SLUG_OF_PLUGIN_CPT_HERE' );`
stackexchange-wordpress
{ "answer_score": 1, "question_score": 2, "tags": "plugin development" }
Change button text with user name using jQuery after user login I have a button to link the login page at the top and after login I want the "Login" text of the button to be "Hi Username - Logout". my link is : <a class="btn mylogin" href="/profile/">Login</a> Any help? Thank you. P.S. Working on the Wordpress 4.7.5
Use this code bellow: <?php if ( is_user_logged_in() ) : ?> <li> <a href="<?php echo wp_logout_url( get_permalink() ); ?>">Logout</a></li> <?php else : ?> <li> <a href=" <?php endif;?> **UPDATE** <?php if ( is_user_logged_in() ) : $current_user = wp_get_current_user(); ?> <li> <a href="<?php echo wp_logout_url( get_permalink() ); ?>">Logout</a></li> <li>Username: <?php echo $current_user->user_login; ?></li> <?php else : ?> <li> <a href=" <?php endif;?>
stackexchange-wordpress
{ "answer_score": 0, "question_score": 0, "tags": "jquery, login" }
Script not working in Wordpress This is the rotation script for images <script> var image = new Array (); image[0] = " image[1] = " image[2] = "images/banner3.png"; image[3] = "images/banner4.png"; var size = image.length var x = Math.floor(size*Math.random()) $('#banner1').attr('src',image[x]); </script> and this is the output to display <img id='banner1'/> Testing it here to see if the script works, and it does < but on my website, it's not working. I am using Simple Custom CSS and JS plugin for the script and img tag placed in the page, the location of my choice, but it's not working. This code for fixed 1 image is working without issues <a href=" <img src="images/banner3.png""> </a> I am here looking for any suggestions that could solve this problem.
Your script doesn't work because you're using `$`. When WordPress loads jQuery, it does so using no-conflict mode. This disables the `$`. Replace is with a `jQuery` instead.
stackexchange-wordpress
{ "answer_score": 0, "question_score": -2, "tags": "images, javascript" }
Plugins successfully uploaded via FTP but they are not on my site I have a problem with my FTP uploads. I'm trying to upload my plugins via FTP like always, but this time, plugins are not on my site. I have check the permissions (755-644): ![enter image description here]( ![enter image description here]( If I install plugins via wordpress admin panel, they appear without problems. I have installed more than 100 wordpress, but it's first time it happens to me. Thank you so much. PS: I also tryed to install one by one, but the result is the same. I have checked and the files are on the server.
Solution found. In this case, the problem was the path name. It included a folder with a keyword that the server should reject: "worm". While for the template was not a problem, for the plugins folder it was.
stackexchange-wordpress
{ "answer_score": 1, "question_score": 0, "tags": "plugins, ftp" }
How to delete users from a WordPress MultiSite that stay in the DB? How can I tell WordPress to remove deleted users from the database automatically? I found that I can go into phpMyAdmin > wp_signups and manually remove them, but this would be a hassle for those that admin my site. I've been spending 2 days looking for plugins, code snippets and hacks but I can't find a way to accomplish this. Can someone please help with this major issue?
Assuming there is some commonality between the users you want to delete, you might look at the answers to this question: Delete all subscribers from wp_users and wp_usermeta a few thousand at a time Make sure you have a backup of your database, though, as an error in the selection of the users could delete important users (like admins). If you are going to go this route, test the sql statement first to ensure you didn't select a critical user, or one that you really don't want to delete. In fact, I'd copy the WP database, and then 'practice' on that database.
stackexchange-wordpress
{ "answer_score": 1, "question_score": 0, "tags": "multisite, buddypress" }