INSTRUCTION
stringlengths
11
999
RESPONSE
stringlengths
0
999
SOURCE
stringlengths
16
38
METADATA
dict
get approved users only ( ultimate member plugin ) I am using UltimateMember and I have the settings configured that admin must approve registered users first. I now want to display the approved users meta information like faculty, email, etc. in the theme. So in this page template I've the following block of code to get all registered users information : <?php $args = array( 'role' => 'contributor', ); $users = get_users( $args ); foreach ( $users as $user ) { echo '<span>' . esc_html( $user->user_email ) . '</span>'; echo '<span>' . esc_html( $user->faculty ) . '</span>'; echo '<span>' . esc_html( $user->graduation_year ) . '</span>'; } The problem is, that my code block is displaying all registered users information weather it is approved by admin or not.
I assume your WP settings is 1. New User Default Role = contributor If yes, so this block of code shows all the contributor's with account_status = approved; $args = array( 'role' => 'contributor', 'meta_key' => 'account_status', 'meta_value' => 'approved' ); $users = get_users($args); foreach ($users as $user) { echo '<pre>'; print_r( $user ); echo '</pre>'; } <
stackexchange-wordpress
{ "answer_score": 2, "question_score": 1, "tags": "user roles, users" }
Get File Object from wp.Uploader I would like to hook into the wp.Uploader and get the FileList object containing the file to be uploaded. So far I've been able to extend the uploader using the code below, but I can't quite seem to find the "before upload" hook. $.extend( wp.Uploader.prototype, { success : function( file_attachment ){ console.log( file_attachment ); } });
You can't hook it directly as `wp.Uploader` doesn't expose it but you can use its `init()` to hook its internal pluploader instance: add_action( 'admin_print_footer_scripts', function () { ?> <script type="text/javascript"> (function ($) { if (typeof wp.Uploader === 'function') { $.extend( wp.Uploader.prototype, { init : function() { // plupload 'PostInit' this.uploader.bind('BeforeUpload', function(file) { console.log('BeforeUpload file=%o', file); }); }, success : function( file_attachment ) { // plupload 'FileUploaded' console.log( file_attachment ); } }); } })(jQuery); </script> <?php }, 100 );
stackexchange-wordpress
{ "answer_score": 0, "question_score": 1, "tags": "uploads, javascript, plupload, media modal" }
Create tabs inside Plugins Admin Page I am developing my own plugin and I am trying to figure out how to add tabs to my admin page. Is the process similar to how we add meta boxes? Ie, something like add_tab_box(...); and I specify a callback? When I say tabs I mean tabs like below: ![enter image description here](
I advice you to read this topic: Here you can find complete guide making options page with tabbed content. Or you can just copy the html of the tabbed page that you've liked, and use it on your own options page. I made my options page with tabs too, but with api. Tabs and the fields are taken from config array. Here you can see `$aus_tabs` array. And here is the class of options page. This class is used to render the form fields.
stackexchange-wordpress
{ "answer_score": 19, "question_score": 13, "tags": "plugins, admin" }
Why do_shortcode is not executing the shortcode in data-* html attributes? This is on Vanilla installation. I've made a shortcode:- /** * Creates a shortcode for shortcode_use_here * @author Omar Tariq <[email protected]> */ function callback_banana_abc( $args ){ /* Don't echo! Always return */ return 'yay!'; } add_shortcode( 'banana_abc', 'callback_banana_abc' ); And I've made a template that looks like this:- <?php /* * Template Name: Test Template * Description: Hello world. */ $str = '<a href="#" title="[banana_abc]" data-abc="[banana_abc]">[banana_abc]</a>'; echo do_shortcode($str); The output is:- <a href="#" title="yay!" data-abc="[banana_abc]">yay!</a> This is only for data-* attributes. It works fine when used in `title` attribute.
`do_shortcodes_in_html_tags()` runs attributes through `wp_kses_one_attr()` which checks them against `wp_kses_allowed_html( 'post' )` which by default only accepts standard non-data attributes, so you'd have to add your attribute: add_filter( 'wp_kses_allowed_html', function ( $allowedposttags, $context ) { if ( $context == 'post' ) { $allowedposttags['a']['data-abc'] = 1; } return $allowedposttags; }, 10, 2 );
stackexchange-wordpress
{ "answer_score": 9, "question_score": 3, "tags": "shortcode" }
how to get rid of header banner buttons on child themes I had just made my child theme yesterday which is dependent on the parent theme but i was wondering how do i get rid of the header banner buttons which i had inherited from the parents theme from the child theme? if someone could point in the right direction that would be much appreciated. please find the link to my staging website for now: <
my apologises.. I had found the answer to my questions...i forgotten that i had to go under customise to change the header options to omit the buttons. just had to choose none in the header options- header right block content. thanks for your help zakir
stackexchange-wordpress
{ "answer_score": -1, "question_score": 0, "tags": "themes, buttons" }
How to bypass Woocommerce checkout validation from the plugin? I need to bypass any validation process in Woocommerce checkout page when **Process Order** button clicked. What filter or action hooks should I use?
I don't know it's the best way to do or not, but it worked for me. add_filter('woocommerce_after_checkout_validation', 'additional_validation')); function additional_validation($fields) { // bypass all error returned wc_clear_notices(); }
stackexchange-wordpress
{ "answer_score": 0, "question_score": 0, "tags": "woocommerce offtopic, validation" }
Problem in upload wordpress with net2ftb I create a site with free host by auto setting and upload wordpress on it. Now i want to upload a module that i write. But i don't know how to do it ? I hear that i can do it by "net2ftp" Thanks in advance.
I think your software is not good solution for your problem. Use FileZilla to upload wp on a Server.
stackexchange-wordpress
{ "answer_score": 0, "question_score": 0, "tags": "uploads" }
Editing/Removing Secondary Menu from Divi I'm using Divi by ET. I created a custom plugin with the following code to enable separate menus for logged-in and logged-out users. function my_wp_nav_menu_args( Array $args = [] ) { if ( is_user_logged_in() ) $args['menu'] = 'logged-in'; else $args['menu'] = 'logged-out'; return $args; } add_filter( 'wp_nav_menu_args', 'my_wp_nav_menu_args' ); The problem is that Divi now applies this custom menu setting to all menus. I've been trying to disable or at least modify the secondary header but am unable to do so. The footer menu doesn't display by default if nothing is selected, but if I do select any option then the plugin overrides that setting and displays the 'logged-in'/'logged-out' menus only.
Please note, specific support questions to third party themes are off topic, so I will treat this in a general way, you should be able to implement this with your current theme To make your code work on only one menu, you need to target that specific menu only. To do that, you will need to check the current menu item location, and if it mathches a given value, then make your changes. The theme lacation is stored as `$args['theme_location']` You can try the following: ( _Just get the correct menu and change accordingly in the code below_ ) add_filter( 'wp_nav_menu_args', 'my_wp_nav_menu_args', 999 ); function my_wp_nav_menu_args( $args ) { if ( 'MENU LOCATION' == $args['theme_location'] ) { if( is_user_logged_in() ) { $args['menu'] = 'logged-in'; } else { $args['menu'] = 'logged-out'; } } return $args; }
stackexchange-wordpress
{ "answer_score": 0, "question_score": 0, "tags": "menus" }
Is it possible to install Wordpress MU on a subdomain? Times ago I developed a MultiSite Wordpress installation, and now I want to move it from the main root folder to a subdirectory. Is it possible run an MU version of Wordpress in a subfolder directory?
Yes is possible. The only thing is that you will have "two sets" of permalinks: * example.com/2015/07/27 * example.com/new-website/2015/07/27 Here is a codex article that explains that. **Edit 1** : Here is a more detailed article on the topic with it's pros/cons and potential issues.
stackexchange-wordpress
{ "answer_score": 1, "question_score": 0, "tags": "multisite, installation" }
custom post type grid with content in lightbox I'm going around every single wordpress plugin and impossible to find something with this featured . . . . I need a grid list of some custom post type - with inline filter. This is fine and tons of plugin can do this, such as essential grid. Otherwise, on click, I need to display the_content on a lightbox, and I can not find anything with this featured.... They all display post on a new page - or just display the thumbnail - sometime the_title in the lightbox . . . . Any plugin or possibilities to achieve this than somebody know ? It will be fantastic :) Thank you for your time :)
Try the "Responsive Lightbox" plugin and use the "Inline" option. For more info, visit the plugin homepage and scroll down to the "Sample Code" section. First sample is "inline contents". I've used this to build a portfolio from a custom post type. It's simple and works well so far.
stackexchange-wordpress
{ "answer_score": 0, "question_score": 2, "tags": "posts, the content, lightbox" }
Specific text not affected by CSS style First, here is the URL for the page I am struggling with: < On the page I have some p-elements with strong text, that I have modified with the following css: .beer-description strong { display: table-cell; text-transform:uppercase; color:#009444; border-bottom: 1px solid #009444; margin-bottom:5px; } .beer-description:after strong { content: ""; display: table-cell; width: 50%; } I have done this to make the text bold, green, and underlined. However, the first two strong elements "Bryggeri" and "Genre", I would like to not be affected by the css rule, so that they only stay bold, black, and inline. Is this at all possible without changing the HTML, and just by using CSS?
You can do that with CSS pseudo nth-child classes. Here is an example to make first two `strong` black. .beer-description strong:nth-child(1), .beer-description strong:nth-child(2) { color: #404040; } You can modify CSS in this as you wish.
stackexchange-wordpress
{ "answer_score": 0, "question_score": 0, "tags": "css, text" }
Convert simple SQL Query to WordPress query I'm trying to 'batch' update the value in my post_parent fields in my wp_posts table. I can do it from within phpmyadmin using the following SQL Query: UPDATE wp_posts SET post_parent = '8' WHERE post_type = 'the_name_of_my_post-type_here'; but I can't get it to work from within wordpress. Any thoughts?
The function you are looking for is `wp_update_post()`. You would want to have your posts which you want to update, then set up a loop to update each one individually. // However you get your posts, ID's, etc. $posts = get_posts( array( 'post_type' => 'post' ) ); for ( $posts as $post ) { wp_update_post( array( 'ID' => $post->ID, 'post_parent' => 8 ) ); } For a generic SQL call, look at the `$wpdb` object, and it's `prepare` and `query` functions: global $wpdb; $query = $wpdb->prepare( 'UPDATE wp_posts SET post_parent = %d WHERE post_type = %s', 8, 'my-post-type' ); $wpdb->query( $query ); You could also look into `$wpdb->update` \- it may suit your needs better in the future.
stackexchange-wordpress
{ "answer_score": 1, "question_score": 1, "tags": "custom post types, mysql, wpdb" }
Dealing with html forms I want to work with html form but i cant understand the Action method and when we need to use it. For example found this code on w3schools: <form action="action_page.php"> First name:<br> <input type="text" value="Mickey"> <br> Last name:<br> <input type="text" name="lastname" value="Mouse"> <br><br> <input type="submit" value="Submit"> </form> how can we use 'lastname' in other file?
Use the following code: <form action="action_page.php" method="post"> First name:<br> <input type="text" name="firstname" value=""> <br> Last name:<br> <input type="text" name="lastname" value=""> <br> <input type="submit" value="Submit"> </form> and in file "action_page.php" Use the following code: $firstname = $_POST["firstname"]; $lastname = $_POST["lastname"]; You can read the information with the following code: <pre> <?php print_r($_POST); ؟> </pre> or var_dump($_POST);
stackexchange-wordpress
{ "answer_score": 0, "question_score": 0, "tags": "actions, forms, html" }
Change directory where get_header(), get_footer() and get_sidebar() look for templates I'm creating my own theme framework, and I want to organize my code, separating the partials files from the pages. But I want to do that and still use the native functions `get_header()`, `get_footer()` and `get_sidebar()`. How can I change this functions to look for the templates on the directory `partials/` instead of the theme's root directory?
Simple solution, use `get_template_part()`. For example: get_template_part( 'partials/footer' ); Which would get the `footer.php` inside the `partials/` directory. Another example: get_template_part( 'partials/footer', 'home' ); Which would get the `footer-home.php` inside the `partials/` directory. One more example: get_template_part( 'partials/footer/blog' ); Which would get the `blog.php` inside the `partials/footer/` directory.
stackexchange-wordpress
{ "answer_score": 3, "question_score": 2, "tags": "templates, sidebar, headers, footer" }
How to check if wp_update_post was successful I want to update a post using wp_update_post( $my_post ); How can I check if it was successful? Should it return the post ID on successful update? I'm trying this: $post_id = wp_update_post( $my_post ); if ( $post_id ) { echo "successful"; } else { echo "fail"; } The above code does not return any ID, so i wanted to make sure if it is correct.
You can use the `$wp_error` argument to return an error message. $post_id = wp_update_post( $my_post, true ); if ( is_wp_error( $post_id ) ) { echo $post_id->get_error_message(); } else { echo 'true'; }
stackexchange-wordpress
{ "answer_score": 4, "question_score": 2, "tags": "plugins, wp update post, wp error" }
how to run a php code in widget? I have a code to get all taxonomies and terms for a single post: $object_terms = wp_get_object_terms($post->ID, 'staff', array('fields' => 'all')); if ($object_terms) { echo '<p>' . '' . '' ; $res = ''; foreach ($object_terms as $term) { $res .= '<a href="' . esc_attr(get_term_link($term, $taxonomy)) . '" title="' . sprintf(__("View artiles of: %s"), $term->name) . '" ' . '>' . $term->name . '</a>, '; } echo rtrim($res,' ,').' ' . '</p>'; } the code works well when i put it in the single post php file. But when i try to put it in a widget using a special php code widget it shows nothing. I tried other php codes in that widget and they run fine but this didn't. Any help please?
Try this with or without the return. $object_terms = wp_get_object_terms($GLOBALS['post']->ID, 'staff', array('fields' => 'all')); if ($object_terms) { echo '<p>' . '' . '' ; $res = ''; foreach ($object_terms as $term) { $res .= '<a href="' . esc_attr(get_term_link($term, $taxonomy)) . '" title="' . sprintf(__("View artiles of: %s"), $term->name) . '" ' . '>' . $term->name . '</a>, '; } echo rtrim($res,' ,').' ' . '</p>'; }
stackexchange-wordpress
{ "answer_score": 0, "question_score": 0, "tags": "php, widgets, sidebar, code" }
Get date numerical and separate? I need to work with date function but I want to get day and month numerical and separate and pass it to a function. For example, I want work for this function. function(day,month) How can I get date of today on pass it to a function aside?
I think this will work for you (tried it and it works): date('m', strtotime('0 month')); date('d', strtotime('0 day')); Here is a discussion on the topic.
stackexchange-wordpress
{ "answer_score": 0, "question_score": 1, "tags": "php, functions, date, date time" }
Adding regex filter to feedwordpress I'm trying to write a plugin for Feedwordpress that filters html from the incoming feeds. So far I have managed to hook it to the right place, but the function completely wipes all content (and it seems to cause issues with the Feedwordpress plugin). Where am I going wrong here? add_filter( /*hook=*/ 'syndicated_item_content', /*function=*/ 'fwp_rss_regex', /*order=*/ 10, /*arguments=*/ 1 ); function fwp_rss_regex ($post) { $content = $post->post_content(); $content = preg_replace('\<[^\>]*\>', '', $content); return $content; }
Fixed it with: function fwp_rss_regex ($content) { $content = preg_replace('/\<[^\>]*\>/i','',$content); return $content; } This solved the problem: 1) Because `$content` was the item I wanted I wanted to pass through fwp_rss_regex, 2) Because I fixed my `preg_replace` with `/______/i` , and 3) I realised `$content = $post->post_content();` was either a superfluous (though maybe valid) command, or was it doing nothing in at all.
stackexchange-wordpress
{ "answer_score": 0, "question_score": 1, "tags": "plugins, php, regex, feed" }
Hook for altering the content of all wp mails Hi i want to set email template for all mails for my site . I know how to set up mail template and i set mail template for each of my mail by editing the code ie wp_mail( $recipient, $subject, $body, $headers, $attachments ); is mail code then i replaced it with ob_start(); require_once (get_template_directory() . '/mail-templates/contacemail.php'); $html2 = ob_get_contents(); ob_end_clean(); return wp_mail( $recipient, $subject, $html2, $headers, $attachments ); now email template is set up for this mail.[here in contacemail.php echo $body; get the content of body] Now i need to do for all my emails rather than editing this code for indivdual mails. How to do that? Is there any hook or filter available? please help.
Yes, there is a filter for this. The correct filter is `wp_mail` and is defined in /wp-includes/pluggable.php Line 135 So the code (maybe in your functions.php) should look something like this: function mail_template($args){ ob_start(); require_once (get_template_directory() . '/mail-templates/contacemail.php'); $args['message'] = ob_get_contents(); ob_end_clean(); return $args; } add_filter('wp_mail', 'mail_template');
stackexchange-wordpress
{ "answer_score": 1, "question_score": 0, "tags": "plugins, functions, filters, hooks" }
Different image margins on different pages CSS I am working on my webpage, where I have several descriptions of beers. Two examples are these two: < and < My goal is to get all of the text aligned so that the text does not wrap around the image. But since there are different amounts of text on the different pages (as is the case with the two links) I cannot set a fixed margin-bottom after the images, which would work with just one picture. Is there a way to do this, so I do not have to depend on different image sizes and different amounts of text? And is it possible with CSS?
You would need to recode your CSS a little. Since you have your beer image in its own container that helps. But you'd want to adjust the CSS: .beer-description{ float: left; width: 70%; } You can tweak it as needed. To not worry about the image size, you should have a width set (can be a percentage) on the `beer-image` container and then 100% width on the `.beer-image img`
stackexchange-wordpress
{ "answer_score": 0, "question_score": 0, "tags": "images" }
Recreating a local repository from a currently existing wordpress.org repo..which I own Sorry for the name. Not sure how to succinctly title this one. I have a plugin available on the WordPress.org repo. It's the Encrypt Email plugin. The laptop I was using to develop/maintain it died. Now I want to resume development of on my work pc. But I'm not sure how. So how can I clone/pull the repo to my machine so I can resume pushing and committing future changes from where I left off? (As if I was still on my dead Laptop's repo) I have TortoiseSVN and can SVN from the commandline so either explanation is fine (I prefer shell to be honest). I have a lot of Git experience so explaining with comparisons to Git commands and workflows would be really helpful for me also. Huge thank you for any help on this one!
Use this URL format for checkout (if using TortoiseSVN, just right click and do checkout from Explorer): ` You will need to use your username/password for WordPress (the account used to publish the plugin) to do any commits. Command line instructions are available direct from WordPress here: <
stackexchange-wordpress
{ "answer_score": 1, "question_score": 1, "tags": "plugins, svn, repository, plugin repository" }
How To Load Different CSS Style, Based On Language When Using QtranslateX I want to use custom css style for every language on my site. I'm using Plugin Qtranslate-x, how can I achieve this?
You have lots of options to achieve this. First of all, the easy way: Qtranslate-X adds a language class to your body tag. So if you want to only have minor tweaks, you can use this in your style.css: .de #page { background:#000; } .en #page { background:#FFF; } If you need big changes (like, you need different css-files per language), you can use the function `qtranxf_getLanguage()` in your themes enqueue_scripts action like this: Lets say you save your styles for german language version in the file `styles-de.css` and for english language in `styles-en.css`. You now enqueue the correct style like this: function mytheme_language_scripts() { $langcode = qtranxf_getLanguage(); wp_enqueue_style( 'lang-style', bloginfo('stylesheet-directory').'/styles-'.$langcode.'.css' ); } add_action( 'wp_enqueue_scripts', 'mytheme_language_scripts' ); Happy Coding, Kuchenundkakao
stackexchange-wordpress
{ "answer_score": 1, "question_score": 1, "tags": "css" }
multiple wordpress installation with shared usertable on an different database I have multiple wordpress installation, and I would like them to share the same usertable. The wordpress installations are already up and running, and they all have their own database. Is it possible to somehow define the users database too and not only the table in the database? define( 'CUSTOM_USER_TABLE', $table_prefix.'my_users' ); define( 'CUSTOM_USER_META_TABLE', $table_prefix.'my_usermeta' ); Any help appreciated.
After writing those two lines in wp-config.php, your users data will be shared between both installations, but both installations will also need to have the same cookie parameters, so in wp-config.php file of your second installation, modify the COOKIE_DOMAIN like this: define('COOKIE_DOMAIN', '.{yoursite.com}'); //replace with URL of first site define('COOKIEPATH', '/');
stackexchange-wordpress
{ "answer_score": 2, "question_score": 0, "tags": "database, users, shared user tables" }
Is it possible to change the template_directory? I've created a site on a localhost that is going to be migrated to a ssl server, with the scripts, css, images all coming from a CDN. To call files in the site i'm using `bloginfo('template_directory');` is there a way to alter this to fit with the sites requirements?
You can filter `template_directory_uri`: <?php add_filter( 'template_directory_uri', function( $template_dir_uri ){ return str_replace( ' ' $template_dir_uri ); }); This will change URIs so they point at a CDN subdomain served via HTTPS.
stackexchange-wordpress
{ "answer_score": 3, "question_score": 2, "tags": "bloginfo" }
Moving a plugin js to footer So, a js from a plugin is located in the header based on the setting below: wp_register_script('plugin_min', plugin_url . 'scripts/scripts.min.js' ); Now, I can change it so that it will be located in the footer by editing the plugin file: wp_register_script('plugin_min', plugin_url . 'scripts/scripts.min.js', array(), false, true ); Of course editing the plugin file is not a good idea since it will be overwritten upon update. So, to do it properly, should I deregister it first then re-register in the function.php?
Your thought is correct. By editing the plugin file you lose updatability. So unregistering and reregistering it in the functions.php would be the correct way to do it.
stackexchange-wordpress
{ "answer_score": 2, "question_score": 0, "tags": "plugins" }
How to call post title and post summary to other part of site? My blog is installed at `/posts` of my site. It's not a mistake; I wanted to be like that. But now my homepage looks somewhat empty. Here I want to call the title of my blog to my homepage, with a link to the original post at `/posts`, followed by a summary of the post. I don't know where to start; I actually have no any technical understanding of WordPress and how it works. My blog is currently installed at <
There are two methods: The one mentioned in this question. And the one mentioned in this Codex page.
stackexchange-wordpress
{ "answer_score": 0, "question_score": 0, "tags": "php, posts" }
How to download Wordpress 4.2.0 I am trying to download Wordpress 4.2.0, not 4.2.3. I go to the downloads page here < Every time I download 4.2 and install it, the admin tells me that 4.2.3 is installed. Why does the link that says "4.2" download 4.2.3? Am I missing something?
Perhaps it's auto-update (since 4.2.3 is a security one). Try disabling the auto updates prior to WP installation via wp-config.php. Here is an article on that. Follow the "Famous 5-Minute Install" but rename manually the wp-config.php file and disable the auto updates first before proceeding installing the WP.
stackexchange-wordpress
{ "answer_score": 2, "question_score": 1, "tags": "installation" }
How to get rid off default css styles I have installed html5 blank template and I have created sub theme too by creating `style.css` and `functions.php`. But how should I get rid off default CSS styles that come from parent theme?
there are two ways, first: if you want to remove default style, just dequeue them using `wp_dequeue_style( 'style_file_name_here' )`. second: you can rename the existing file and create a new one with the same name, just place style hook info into new style file, like: /* Theme Name: Theme name Author: Author name */ remember, the second way is unprofessional, but you can use this one as well.
stackexchange-wordpress
{ "answer_score": 3, "question_score": 0, "tags": "wp enqueue style" }
Wordpress rewrite rules not working I have created a plugin and i have gotten rewrite rules to work using my .htaccess file. I would like to make this work from my plugin instead to keep everything contained from within there. Im trying to do this via the wordpress rewrite but nothing i do it working with this. I have even tried a basic rewrite and it wont work either. readme.html is a page in the root directory. I simply want testpage to display this page. The other rules i have in my .htaccess are far more complicated than this so, if i cant get this one to work i have no hope with the complicated ones. add_action('init', 'add_actor_url'); function add_actor_url() { add_rewrite_rule('^testpage','readme.html','top'); flush_rewrite_rules(); }
You need to flush rewrite rules after adding or modifying rewrite rules in WordPress. `flush_rewrite_rules()` can be used to flush rules. For more info check these links : < <
stackexchange-wordpress
{ "answer_score": 1, "question_score": 0, "tags": "plugins, url rewriting, htaccess, rewrite rules" }
how to disable jetpack for non admins? I am using wordpress 4.2.3 and jetpack latest version. All users of my site are contributors. I want to hide jetpack from contributors. I hide the jetpack menu from dashboard by **WP admin UI customize** plugin. But when any user type url: **mysite/wp-admin/admin.php?page=jetpack** it is appearing on browser.I used this code,but not helped me. function ap_remove_jetpack_page( ) { if ( class_exists( 'Jetpack' ) && !current_user_can( 'manage_options' ) ) { remove_menu_page( 'jetpack' ); } } add_action( 'admin_menu', 'ap_remove_jetpack_page', 999 ); ` Escape me !!
Use the code given below, In this code we are checking if page is 'jetpack' and based on that showing custom error message. add_action( 'admin_init', 'restrict_page' ); function restrict_page() { if ( class_exists( 'Jetpack' ) && !current_user_can( 'manage_options' ) ) { if ( isset( $_GET['page'] ) && $_GET['page'] == 'jetpack' ) { wp_die( 'no access' ); } } }
stackexchange-wordpress
{ "answer_score": 0, "question_score": 0, "tags": "plugin jetpack" }
Assign published posts to another user automatically Usually, I write posts as admin, as this is more comfortable from the blog administration point of view. But I want the posts to be assigned automatically to another existing user with editor privileges. How to do this?
You can try using `wp_insert_post_data` for the task. Something like: function assign_new_post_to_specific_author( $data , $postarr ) { // Where author_ID is the ID of the author you want to assign the new post $data['post_author'] = author_ID; return $data; } add_filter( 'wp_insert_post_data', 'assign_new_post_to_specific_author', '99', 2 ); Tried it on c9.io and it works, but you need to check the filter priority for yourself.
stackexchange-wordpress
{ "answer_score": 2, "question_score": 0, "tags": "posts, users, publish" }
how to edit a specific post slug using a php code? I want a php code by which i can show a modified link to the post. when using <?php get_post_permalink(); ?> it shows e.g.: (www.mysite.com/post-name-one). what i need is something like (www.mysite.com/abstract/post-name-one). because adding this word to the link will activate a function to change the post template. I tried to use: <a href="<?php the_permalink(); ?>" title="<?php the_title_attribute(); ?>">Abstract</a> but this shows the original link and i couldn't edit it. so i tried to use: <a href="<?php get_site_url(); ?>/abstract/%post-name%" title="<?php the_title_attribute(); ?>">Abstract</a> but it didn't work. I think there must be a way to add "abstract" to the link after <?php get_site_url(); ?> and before the post name but i couldn't figure it out. Any suggestions please?
try this `$post_id = 11; $post = get_post($post_id); $slug = $post->post_name; <a href="<?php get_site_url(); ?>/abstract/<?php echo $slug; ?>" title="<?php the_title_attribute(); ?>">Abstract</a>`
stackexchange-wordpress
{ "answer_score": 1, "question_score": 0, "tags": "php, posts, permalinks" }
WordPress 4.2.3 on Windows Server 2008 R2 Creating Files as read only Whenever I attempt to update a plugin or change my configuration for W3 Total Cache, if wordpress creates a new file, it's created with the Read Only attribute. I can upload and delete content without issue. It's just updating a plugin or the w3total cache config. I removed the read only attribute from the w3 total cache config file and the changes are saved successfully, subsequent updates fail because the newly created config file is read only. I've confirmed it's PHP-CGI that's changing the attribute, because on the successful config update I see PHP-CGI changing the attribute. I've tried every combination of permissions / ownership I could think of. Including using AppPool identities and "Connect As", running as administrators and non-admins. I'm just not sure why the read only attribute is getting set. ![Image]:
I figured out the issue, my site had the following in wp-config.php. Also WP-config.php had to be placed at the site root define('FS_CHMOD_DIR', true ); define('FS_CHMOD_FILE', true ); define('FS_METHOD', 'direct'); Removing the above resolved the issue.
stackexchange-wordpress
{ "answer_score": 1, "question_score": 0, "tags": "php, plugin w3 total cache" }
How to use WP_Query to display many posts? This is my `WP_Query` instruction but this not work. This display just first post. Help me please? // WP_Query arguments $args = array ( 'post_type' => 'teachers', 'p' => '100, 102, 105' <---------- ); // The Query $filter = new WP_Query( $args ); // The Loop if ( $filter->have_posts() ) { ...
The `p` (post) paremeter for `WP_Query` accetps a single value only: $args = array( 'p' => 100 ); For multiple posts use `post__in` and pass an array of post ids: $args = array( 'post__in' => array(100, 102, 105) ); See Post & Page Paremters for further clarification.
stackexchange-wordpress
{ "answer_score": 2, "question_score": 1, "tags": "wp query, loop" }
How to pass many ids in post__in? I need to pass many ids to the parameter `post__in` in args. This not work !!! Help me please. foreach ($rows as $obj) { $todos .= $obj->ID . ","; } $ids = trim(trim($todos), ","); # echo $ids output -------> 613,647 $args = array ( 'post_type' => 'professores', 'post__in' => array($ids) <----- Don't work ); How to do this work? **Thanks!**
Don't concatenate your id values into a comma separate string otherwise you will have to `explode()` by comma delimiter which is pointless, instead, if you are getting IDs from some other business logic as evidenced in your iteration over `$rows`, then build an array of IDs as per the following example: $ids = array(); foreach ($rows as $obj) { $ids[] = $obj->ID; } $args = array ( 'post_type' => 'professores', 'post__in' => $ids );
stackexchange-wordpress
{ "answer_score": 2, "question_score": 1, "tags": "wp query, loop" }
structure of posts and pages I have wordpress website which had some static pages and posts. I want to show pages URL as below: mywebsite.com/PageName1 mywebsite.com/PageName2 ... also I have some posts that will be more in next, and my desired structure for post url is: mywebsite.com/blog/PostName1 mywebsite.com/blog/PostName2 ... I should say that I make a category with name "Blog" and all of my website posts are in this category. Thanks in advance.
You can configure that in admin panel. Just go »Dashboard > Settings > Permalink« settings.
stackexchange-wordpress
{ "answer_score": 0, "question_score": 0, "tags": "posts, pages, urls" }
Embed and word Count not working for wp_editor instance When using the wp_editor() function to have an editor, I do not see the standard word count and am unable to embed files. In the default post editor, word count is shown, and youtube urls are automatically converted into embeds. What am I missing here? Added the wp_editor with this code:`wp_editor( $data, 'welcome_text', array( 'wpautop' => false, 'textarea_name' => 'welcome_text' ) ); `
So, after discussing this in the #core channel on Slack, got notified the embed and wordcount only work for posts (and CPTs).
stackexchange-wordpress
{ "answer_score": 0, "question_score": 0, "tags": "wp editor" }
How to put an external object into WordPress to that occupies most of the available space? I have a WordPress site. I want to insert into one of its pages another page, written in AngularJS. That page is a Spring Boot system and will be hosted on a different machine than the WordPress page. When I embed that external component into my WordPress I want it to occupy as much space on the screen as possible (see the green rectangle in the screenshot below). ![Screenshot]( If I simply insert it into a page in the usual way (like I insert YouTube videos), then the width of the component is limited by the width of the content part (red rectangle). That's not an option, I need more space. How can I 1. put an external component into a WordPress site, 2. so that it occupies the entire width of the page and 3. all other pages are not affected by this change (have the same theme etc.) ?
Not really a wordpress question, and except for the last option you might get a different and maybe better answers on stack exchange. Three options one ugly, one requires extra work and one is super hard but might be the right thing to do. **Ugly** : Put the external object in an iframe and write some JS that will autommatically adjust the width and height of the iframe to the avaialable space. bonus points for handling browser resize events **Extra work** : Use some Jquery code (Don't have to, but that is what everybody does) to load the external object into memory. Parse it and insert the relevant part into a div on a page (use a shortcode to indicate the location of the div for non techi users) **super hard** : change the external site to support oembed and return the relevant html for requests, change your wordpress to recognize the external site as a valid source for oEmbed. In the post insert the relevant url on the external site.
stackexchange-wordpress
{ "answer_score": 2, "question_score": 0, "tags": "embed" }
How to Login Once to an Entire WP Multisite Network Does anyone know of a good plugin that permits logging in once as the WP-MS network **Super Admin** and being able to switch sites without having to re-login into each network and/or each site individually? Thanks
> @tammy it doesn't. If you have a dozen different network setups then there is no safe and secure way to log in to all of them at once. If they are a dozen sites on 1 WP install then when you log in you should be logged in across a single network. – Alex Older Aug 5 at 10:35
stackexchange-wordpress
{ "answer_score": 2, "question_score": 3, "tags": "multisite, login" }
Contact Form 7 - Execute code AFTER mail send I've figured out how to do something BEFORE sending the mail, but I also need an action to happen AFTER it's been send. I tried `wpcf7_after_send_mail` but with no success... Any help on the matter would be much appreciated.
**EDIT:** Please note that as of 2017 'on_sent_ok' is deprecated. This means that your code will stop working at some point in the future (likely by the end of 2017). The recommended solution is using DOM event listeners directly. For example, if you used: on_sent_ok: "ga( 'send', 'event', 'Contact Form', 'submit' );" You should replace it with: document.addEventListener( 'wpcf7mailsent', function( event ) { ga( 'send', 'event', 'Contact Form', 'submit' ); }, false ); The JavaScript code can be placed e.g. in the footer of your page. **ORIGINAL ANSWER:** Ok figured it out. In the specific form settings, go to the additional fields tab. Type in the following: `on_sent_ok: "location.replace(' It's working like a charm for me now. Hope this helps other developers in the future as well. ![enter image description here]( I know the image is in Dutch ... but you can't miss it with the **big red lines** around the tab name.
stackexchange-wordpress
{ "answer_score": 7, "question_score": 8, "tags": "hooks, plugin contact form 7" }
index.php is always displayed before any file on the URL When I make click at any file from my website, the URL displays like: **www.mywebsite.com/index.php/about-me** OR **www.mywebsite.com/index.php/references** I just want to know if it is normal that index.php gets always displayed before any other file (something like **www.mywebsite.com/about-me** would be more common to see) or if this is some type of error.
First, check if you have an .htaccess file with the following: # BEGIN WordPress <IfModule mod_rewrite.c> RewriteEngine On RewriteBase / RewriteRule ^index\.php$ - [L] RewriteCond %{REQUEST_FILENAME} !-f RewriteCond %{REQUEST_FILENAME} !-d RewriteRule . /index.php [L] </IfModule> # END WordPress If this file already exists with the appropriate rules, try the following: * Go to your site Settings > Permalinks. If there is something already there, make sure you copy it and keep it safe in case it breaks your site. Select one of the defaults and save. * Visit your site and refresh. * If you still have no solution, try a hard refresh on your site - `cmd/ctrl + shift + r`. If you are still having the problem, please go into more detail about the circumstances of your site (version, plugins, theme, etc.) so we can try to better help you.
stackexchange-wordpress
{ "answer_score": 1, "question_score": 1, "tags": "permalinks" }
On a custom template, should I use wp_footer? I have started to learn about WP. I was asking myself the other day : should I use, in my custom template, the wp_footer() to call my scripts or should I go with static script? I can't seem to understand how wp_footer works, tho I know it is a do_action but I actually don't want to change the "core" for wp_footer, I just want to add my own scripts in the footer. Should I go to the function that call wp_head and add my scripts there or should I write it down in a static footer.php like Thx!
<?php function theme_footerscript(){ wp_enqueue_script('main_js', get_template_directory_uri() . '/assets/js/main.js', array('jquery'), '1.0', true); } add_action('wp_enqueue_scripts', 'theme_footerscript'); ?> this way you will add a script on footer (add this code in functions.php). if you set the last parameter to true, then the script will be at the bottom of html page. you can check on Wordpress Codex
stackexchange-wordpress
{ "answer_score": 0, "question_score": 0, "tags": "php" }
<?php the_content(); ?> to get a little more content after 'read more' inside loop I want the to give a little more content after `<!--more-->` tag inside Loop. I saw this on wordpress codex This script gives the content before the `<!--more-->` tag: <?php global $more; // Declare global $more (before the loop). $more = 0; // Set (inside the loop) to display content above the more tag. the_content("More..."); ?> This script gives all the content including text below `<!--more-->` tag: <?php global $more; // Declare global $more (before the loop). $more = 1; // Set (inside the loop) to display all content, including text below more. the_content(); ?> What I want is: Post content until `<!--more-->` tag + a little after (2 lines approx) the `<!--more-->` tag.
You can get the diff between your 2 contents and then add to the first one a given number of words like this (not sure, but give it a try ;) ) : global $more; $more = 0; $content_cut = get_the_content( '' ); $more = 1; $content_full = get_the_content(); // Get the diff $content_diff = str_replace( $content_cut, '', $content_full ); // Get 10 first words $some_more_content = wp_trim_words( $content_diff, 10, 'link_more_here' ); // Add it to the end of cut content $content_cut .= $some_more_content; echo $content_cut; The **linl_more_here** parameter is optionnal and is normaly a tag with the permalink of your current post.
stackexchange-wordpress
{ "answer_score": 0, "question_score": 0, "tags": "loop, excerpt, content" }
Wp_mail() function not working in Windows and MAC OS Not getting mails when sent from Windows OS and MAC OS but getting when sent from Linux OS. I tried sending mails from LINUX OS,Windows and MAC OS LINUX sending me the mails as it should do but windows and MAC failing to send the mail I am getting `Mail sent successful` message, but not getting mails when sent from Windows or Mac OS.
Finally I ended up in succeeding by using this Plugin which converted default Gravity forms Wp-Mail() to SMTP thus received mail from Windows and MAC OS too.
stackexchange-wordpress
{ "answer_score": 0, "question_score": 0, "tags": "wp mail, linux, windows, mac" }
Import Wordpress site to localhost, but loads blank white screen WAMP works fine on my PC. I've created a Wordpress install on `D:/wamp/www`, replacing the default WAMP `index.php`, and I've created a new database. I've exported the database from the remote site, replaced any instances of `www.example.com/` with `localhost/`, and imported this edited database into the db I created earlier. I've created `/wp-config.php` and entered correct db connection details. However ` loads a blank white screen, with no source code. I've set `define('WP_DEBUG', true);` in `wp-config.php`, and no errors show. There is nothing in `D:\wamp\logs\apache_error.log` indicating what the problem is. Any idea what the problem is? Thanks.
Found the error. I was creating a new WP install, importing the DB, but forgot to copy the themes into `/wp-content` !
stackexchange-wordpress
{ "answer_score": 0, "question_score": 0, "tags": "localhost" }
WP-API: get posts in multiple categories Let's say, I have two categories, '`color`' and '`temperature`'. Each one has a number of sub-categories. Wordpress does great job displaying posts in requested categories when I go to URL like this one: Now I would like to do the same with json-rest-api plugin, via REST requests. Is it possible? How to get posts in multiple categories (not in either, but in all of requested) using REST requests? I've tried different URIs, but failed.
Assusming you are using V1 of the WP-API, did you tried the following endpoint: I'm looking at the code in WP_JSON_Posts class and the get_post() should be able to handle that use case. UPDATE: It seems there is a limitation with the way the query is built. Here is a potential workaround: add_filter('json_query_var-category_name', function( $var ) { return str_replace(' ', '+', $filter[ $var ] ); }); Or even better (without new code)! Encode the + in the url with %2B: This seems to work for me! See here for clarifications: < Note: In V2 this endpoint will not work.
stackexchange-wordpress
{ "answer_score": 1, "question_score": 0, "tags": "query posts, wp api" }
List all unique custom field values? I use this code to list unique values of custom field name "authors" from all posts. It works just fine, but I would like to limit results, to get values which appear in at least for example 20 posts? How to drop out custom field values which are in use in less than 20 posts? <ul> <? global $wpdb; $query = "SELECT DISTINCT meta_value FROM $wpdb->postmeta WHERE meta_key = 'authors' ORDER BY meta_value;"; $authors = $wpdb->get_results( $query ); foreach( $authors as $author ) : echo'<li>'; echo $author->meta_value; echo '</li>'; endforeach; ?> </ul>
From what I understand I think you can try something like: SELECT meta_value, COUNT(post_id) as count FROM $wpdb->postmeta WHERE meta_key = 'authors' GROUP BY meta_value HAVING count >= 20 ORDER BY meta_value; Let me know if this works for you!
stackexchange-wordpress
{ "answer_score": 2, "question_score": 0, "tags": "custom field" }
How to retrieve a custom post's capability? When you register a custom post type, you can specify it's capability: 'capability_type' => 'page', Is there away to retrieve the capability_type within a page (based on the post object provided)? I don't see it listed within the post object. But maybe there's a way to retrieve by passing the post_type? The ultimate goal is to find out whether a post is to be treated as a "page" or a "post" on the front-end, which would allow me to load different template/code parts based on that information.
The `get_post_type_object()` function accepts a post type name and returns the post type object. You can then check the `capability_type` property of this object. Example: $post = get_post( $post_id ); $pto = get_post_type_object( $post->post_type ); $cap_type = $pto->capability_type;
stackexchange-wordpress
{ "answer_score": 4, "question_score": 1, "tags": "custom post types, post type" }
Search Page: activate html code if the tag is on the page this is the first time that I write here and my English is not very good, I will try to explain as best as possible. I want to activate some html text if in the result page, the results, has a particular tag. For example: i have pages with the "locations" tag. If I do a search, I wish in the search results, appears html code if the tag of the page reference is "locations". if the tags of the page is different, it should not appear nothing. I'm looking for in the conditional tags, but I can not find anything like that. I could express myself well? Thanks
This is completely untested but I believe you would want something along these lines: <?php if( $loop->have_posts() ): while ( $loop->have_posts() ): $loop->the_post(); // Do stuff for results echo '<h2>' . the_title() . '</h2>'; // Check for tag if(has_tag($tag) { output HTML if true } endwhile; else: echo "No Results!"; endif; ?>
stackexchange-wordpress
{ "answer_score": 0, "question_score": 0, "tags": "pages, search, tags, conditional tags" }
I would like to add ssl certificate to my already existing wordpress site I have site named as www.splessons.com and it has 500 articles and now i would like to add ssl certificate to it. My doubt is does this effect to my old articles. Doubts: 1) Does it effects to my old articles ? 2) Some of images have in articles like www.splessons.com/images/splessons.jpg what will happen after i add ssl to my site. I mean after adding ssl, < will work fine or not ? 3) Do i need to take any precautions ? Thanks, Hari
1. Yes it applies to your old articles. 2. There are several specific issues related to images which use **absolute urls** (mixed content errors). Basically you need to inform plugin/theme authors to update their code or to update it yourself (which is not recommended because in case of update you will lose the changes.) 3. Yes. After applying the certificate you need to check for mixed content errors and to fix them. They usually are connected to: * improper enqueueing of scripts and styles using absolute urls * using absolute urls in images, pages and etc. Here is a good article on how to apply SSL certificate and how to handle mixed content errors. **Remember to backup your website and database prior to applying the certificate!**
stackexchange-wordpress
{ "answer_score": 0, "question_score": 0, "tags": "ssl" }
Why is this $wpdb query looping 5 times? I want to only return one value for this query, it's in my `functions.php` file. The idea is to return a value that I need once `post_meta` has been updated. It's returning the same (correct) value _5 times_... I only want the value to be returned once. add_action( 'added_post_meta', function ( $mid, $object_id, $meta_key, $_meta_value) { global $wpdb; $table_name = $wpdb->prefix . 'postmeta'; $results = $wpdb->get_var( "SELECT meta_value FROM " . $table_name . " WHERE meta_key = 'data19' AND post_id = " .$object_id. " " ); }, 10, 4 ); Any ideas how I can get just one value returned? I've tried: * adding `Group by` to the end * adding `OBJECT_K` to the end * using `SELECT DISTINCT` * using `MAX` before each value * using `FIRST` before each value * using `wp_reset_query()` and some more I can't even recall.
The most likely cause is that the hook is probably running multiple times (e.g. once per meta field). You may need to qualify/filter your function like so… add_action( 'added_post_meta', function ( $mid, $object_id, $meta_key, $_meta_value) { global $wpdb; if ( $meta_key != 'data19' ) { return; } $table_name = $wpdb->prefix . 'postmeta'; $results = $wpdb->get_var( "SELECT meta_value FROM " . $table_name . " WHERE meta_key = 'data19' AND post_id = " .$object_id. " " ); }, 10, 4 );
stackexchange-wordpress
{ "answer_score": 1, "question_score": 0, "tags": "wpdb" }
Display random text from a file with the WP built-in AJAX API I want to use a solution by @toscho to display and rotate some quotes. The unchanged code works very well, but if I replace the protected function get_rand() { return rand( 1, 1000 ); } with (from here) protected function get_rand() { $array = file("wp-content/plugins/quotes-rotator/quotes.txt"); $r = rand(0,count($array)-1); return $array[rand(0,count($array)-1)]; } the code works well only at the first page load, but when I press the 'New' button to display a new quote the system outputs an error: > Warning: file(wp-content/plugins/quotes-rotator/quotes.txt): failed to open stream: No such file or directory in /var/www/.../public_html/wp-content/plugins/quotes-rotator/ajax-shortcode-demo.php on line 106 **What is wrong here?**
to have the good path to the file, try this : `$array = file(plugin_dir_path(__FILE__) . "quotes.txt");`
stackexchange-wordpress
{ "answer_score": 1, "question_score": 0, "tags": "functions, shortcode, ajax" }
How to add wpmode in Flash Embed Code in WordPress Site? I am very new to WordPress, and I want to Embed Flash in my website. I tried some plugin but it does not work. I consulted with some developers, and they said, I need to put, _wpmode=direct_ as param in my Flash Embed Code. How do I add wpmode in embed code. Please Help. Thanks in Advance.
You can try this plugin. Anywhere Flash Embed You can use ShortCodes like [swf src="http:/:/www.example.com/my-flash-file.swf" width="600" height="300" params="wpmode=driect"] This should help. For detail instruction, please see plugins page.
stackexchange-wordpress
{ "answer_score": 0, "question_score": 0, "tags": "plugins, flash" }
How can I get I get the thumbnail custom size dimensions? Assuming I have a custom thumbnail size, as defined by the following... add_image_size( $name, $dim_x, $dim_y, true ); ...how can I get the defined image dimensions programatically, using only $name ?
If you take the look at the source of the function is simply stores the arguments in `$_wp_additional_image_sizes` global, with key by name. As far as I remember there are no dedicated API functions for it (`get_intermediate_image_sizes()` will return list of names, but not data). Just access the global and look for data you need by key.
stackexchange-wordpress
{ "answer_score": 1, "question_score": 1, "tags": "thumbnails, images" }
404 error on all pages but homepage I have a local install of wordpress home page is accessible at < Backend is accessible at < etc No other front end urls are accessible, they return 404 I have refreshed permalinks, and tested apache mod_rewrite is on with this script < Any ideas?
Assuming you are on Linux, you need to make some changes in apache2.conf file stored in /etc/apache2 directory. Open the file with root permissions, you will find the code given below in the file. <Directory /var/www/> Options Indexes FollowSymLinks AllowOverride None Require all granted </Directory> Here just change the `AllowOverride None` to `AllowOverride All`, save the file & restart apache. This will work in most of the cases.
stackexchange-wordpress
{ "answer_score": 1, "question_score": 0, "tags": "404 error, local installation" }
Use __($str) and _e($str) to translate strings with HTML I'm currently developing a non-trivial theme right now, most of the time I'm not using a `__($str)` translate function when there's an HTML tag therein the text. Is it good to always use the translate functions such `__($str)` and `_e($str)` whenever there's a text that'll be going to output? Any downside with it? Can I still use it even to a very long text that have mixed with an HTML tag such like this? __("This <em>text</em> have an <b>HTML</b> tag. Another sentence...") Or it is good to use like this? _(*Looks messy..)_ __('This ').'<em>'.__('text').'</em>'.' have an '.'<b>'.__('HTML').'</b>'__(' tag.') How to properly use such kind of a function?
The sweet and short of it all is, never try to translate HTML tags. Use placeholders and either `printf` or `sprintf` to translate strings with HTML tags Something like this will do ## `printf()` printf( __( 'This %s text %s have an %s HTML %s tag. Another sentence...' ), '<em>', '</em>', '<b>', '</b>' ); ## `sprintf()` sprintf( __( 'This %s text %s have an %s HTML %s tag. Another sentence...' ), '<em>', '</em>', '<b>', '</b>' );
stackexchange-wordpress
{ "answer_score": 3, "question_score": 5, "tags": "theme development, localization" }
Is there a restriction in WP on the use of jQuery load function? I'm just trying to load a simple txt file for testing purposes. jQuery(document).ready(function(){ jQuery("#buttonAjax").click(function(){ jQuery("#demo").load("demo.txt"); alert('inside jquery'); }); }); The code works because the alert works, but it doesn't load demo.txt (Hello Im demo text). I tried one solution I found on SO and it doesn't work either: jQuery(document).ready(function(){ jQuery(document).on('click', '#buttonAjax', function() { alert("inside ajax"); jQuery("#demo").load("demo.txt"); }); }); I am aware of wp_localize and WP ajax, I read the Codex, but I just want to make the load method work. <p id="demo"></p> PS. If it's a duplicate (not ajax, but showing to make load work) please post it in comments, don't just blindly downvote.
You should always use a full URI when specifying a location of a resource (in this case a file). With relative URIs like you use for you data file here, the URI will be appended to the URL in the address bar which will result in surprising URLs when you use permalinks. In practice the pattern for developing such thing is to upload the files via the admin and use the URL you get via the attachment API. This way you do not need to assume anything about which part of the server are accessible to the user. If it is part of a theme, then you do know where it i located, just use the proper theme api to get the theme's root url.
stackexchange-wordpress
{ "answer_score": 2, "question_score": 1, "tags": "jquery, ajax" }
What is the purpose of the option name hack_file in the options table? I was looking at the options table in a WordPress install and noticed an option name hack_file. At first I thought the site was compromised and then realized it is a default option < . I couldn't find much information regarding it. What is it and its purpose?
As the codex says, it is legacy with probably no use in any modern version. I have been around wordpress since 2.0.4 and I don't remember it being used or referenced so my guess is that it is a really old legacy thing.
stackexchange-wordpress
{ "answer_score": 7, "question_score": 7, "tags": "database, options" }
How to post data to same page in wordpress I am trying to submit form and get that data in same page when i used the_permalink i am getting page not found. I used this code: <?php /* Template Name:testing */ if(isset($_POST["name"])) { echo $_POST["name"]; } ?> <form action="<?php the_permalink(); ?>" method="POST"> <input type="text" name="name" id="name"> <input type="submit" value="submit"> </form>
Do not use any action in form. If you keep empty action of form then data will submit on same page if(isset($_POST["name"])) { echo $_POST["name"]; } <form action="" method="POST"> <input type="text" name="names" id="names"> <input type="submit" value="submit" name="submit_btn"> </form>
stackexchange-wordpress
{ "answer_score": 5, "question_score": 7, "tags": "plugin development, theme development" }
Dropdown switching subcategories portfolio I have portfolio on my site and i want add dropdown switching subcategories for taxanomy 'potfolio-types' For example: > Category A > > * subcategory 1 > * subcategory 2 > * etc... > when're in category A, the drop-down list shows the child category. When selecting child category, go to her. I use this code <?php $args = array('hide_empty'=>1,'depth'=>1,'hierarchical'=> 0, 'show_count'=> 1,'taxonomy'=> 'portfolio-types',); ?> <ul> <?php wp_dropdown_categories( $args ); ?> </ul> But the list shows all the categories and subcategories. And there is no transition.
The 'child_of' argument lets you select subcategories from a parent category, and a you can get the current taxonomy id to pass as the value: <?php $category_id = get_queried_object_id(); $args = array( 'hide_empty'=>1, 'depth'=>1, 'hierarchical'=> 0, 'show_count'=> 1, 'taxonomy'=> 'portfolio-types', 'child_of' => $category_id ); ?> <ul> <?php wp_dropdown_categories( $args ); ?> </ul> So in the example above, only children (sub-categories) of portfolio-type of the current category ID will be displayed. Note that this code will only work if you are in a taxonomy archive page, which I think that's what you intend to do.
stackexchange-wordpress
{ "answer_score": 0, "question_score": 0, "tags": "custom post types, categories, custom taxonomy, filters, dropdown" }
Create a regular post for every WooCommerce order I'm trying to make a post, which will list product meta(every order will have only one product) and on that post I want to make visible product variations. So the link will be generated and sent to users mail (I have an idea of sending that email). So whenever the order is created, I need a post for every one order. I only need a direction, in which way should I look. Thanks in advance.
in comments I propose to make the order as public but I found a easier way to display a order : with a shortcode i try this in a plugin : add_shortcode("view_order", function ($atts, $content = "", $tag) { if (!isset($_GET["order_id"])) { return "no id"; } $order = get_post($_GET["order_id"]); if ( !isset($order) || ("shop_order" !== $order->post_type) ) { return "no shop_order"; } // result of the shortcode ob_start(); echo "<pre>"; print_r($order); echo "</pre>"; return ob_get_clean(); }); . then in a page ("preview order" in my exemple) put the shortcode `[view_order]` and you can see the details of the order on the URL : <
stackexchange-wordpress
{ "answer_score": 1, "question_score": 0, "tags": "woocommerce offtopic, order, e commerce" }
Moving to a new domain in the same server I recently adquired a new domain I would like to use for my old wordpress site. I managed to configure this new domain in the same server and pointing to the main page. However, after changing the `Wordpress URL` and `website URL` fields under `Settings`, the layout for the site breaks. It's like the theme I'm using gets corrupted. What is the correct way of switching from one domain to another? I looked at < but this doesn't mention the case when both domains are under the same server. Thanks for your help,
You are facing the error because the database tables have old domain stored in all tables and post meta data. You need to replace all instances of previous domain with the new one in the database, the following link will help: < You should also update your permalinks after the above process.
stackexchange-wordpress
{ "answer_score": 4, "question_score": 2, "tags": "installation, domain" }
Search buddypress groups with querystring in url If you wanted to search groups in buddypress you can simply navigate to (< But is it possible to pass other parameters to url like orderby=membernumbers&order=ASC or tags= or search exact phrase ... . So I'm wondering if any of these actions is possible? 1- Sort group search results based on number of members 2- Search groups Only by their Tags... . 3- Search grous based on tags with exact phrases only.
Not in the url, but you can pass other parameters in the groups loop. There is a `search_terms` parameter in `bp_has_groups()`. It also has an `orderby` parameter that accepts `total_member_count` as the property. Assuming the tag info is stored in group_meta, you can add a meta_query parameter to the `bp_has_groups()`. More info from the BuddyPress codex.
stackexchange-wordpress
{ "answer_score": 2, "question_score": 0, "tags": "search, buddypress" }
New post from database I have data stored in DB (mysql) I want to creat new post for each row I have created custom post type with custom fields Beside xml rpc is there any other way. Cheers
With few lines of code you can transfer your data from your custom table to post table. 1. Do some `MySQL query` using $wpdb Object to get data from your custom table. 2. And then in foreach() loop use `wp_insert_post` and `add_post_meta` to add all those rows in your post table. And you are Done!
stackexchange-wordpress
{ "answer_score": 1, "question_score": 0, "tags": "custom post types, mysql" }
Counting posts in custom post type by author I have googled this a few different ways, but cannot find the answer I'm looking for. I want to be able to count the number of posts each author has within a custom post type. Any suggestions would be really appreciated
i found this code wordpress.org . This code would work in author template. <?php global $wp_query; $curauth = $wp_query->get_queried_object(); $post_count = $wpdb->get_var("SELECT COUNT(*) FROM $wpdb->posts WHERE post_author = '" . $curauth->ID . "' AND post_type = 'post' AND post_status = 'publish'"); ?> <h2>Post Count: <?php echo $post_count; ?></h2> But if you wish to use it somewhere else then replace `$curauth->ID` with author id and `post` with the post type you want it should work . All the best
stackexchange-wordpress
{ "answer_score": 0, "question_score": 0, "tags": "count" }
Pre-selecting the category for a custom post type I have a custom post type that has 6 available categories. The categories are used as column headings in a table with their corresponding posts in that column. I want to be able to click on the heading (category name) which will be an anchor tag and open the add new post page in the admin area with the category selected. Does anyone have any ideas on this please?
in my exemple, "CPT" stands for the slug of your custom post type. # First step : Using the link of "create new CPT" to add the information of category. for exemple the result would look like # Second step : Using the hook `save_post_CPT` to preset the category. it would be something like that : add_action("save_post_CPT", function ($post_ID, $post, $update) { if ($update) { // it's not a new object return; } if (!isset($_GET["category"])) { return; } // setting the category wp_set_object_terms($post_ID, $_GET["category"], "category", TRUE); }, 10, 3);
stackexchange-wordpress
{ "answer_score": 0, "question_score": 1, "tags": "custom post types, categories" }
template structure for CPT not clear I am a little confused with CPT and custom taxonomies. I created CPT named 'Profiles' and did not create any custom taxonomies for it. So categories is the default taxonomy for it, I tried template, 'taxonomy-php.php' (ie my category in CPT) , but it displayed nothing. Dont know whats the issue, I also tried 'category-php.php' but it also didnt work. The code is correct i worked it for normal loop and it ran smoothly, please suggest me the right structure.
Sorry I was using wrong structure, after looking through a bit more i found out exact difference for CPT and cutom taxonomies. For custom post types the template structure is like:-\ single-{post-type}.php archive-{post-type}.php search.php index.php And for Custom taxonomies, the template structure I found out from here:- Link:-Templates for Custom Post Types and Custom Taxonomies
stackexchange-wordpress
{ "answer_score": 0, "question_score": 0, "tags": "custom post types, custom taxonomy, templates" }
Facebook like update status for wordpress I am new to wordpress and i am learning a lot. But i am making this intranet site and i need to make a form just like Facebook's update status where my logged in users will need to update their status or upload some images with a description on it. Then underneath that, i will need to have a comment section and like buttons. I know i could use the create post form on the front page but the status won't be having a title. Attached is an image just to show what i am trying to achieve. Any ideas will be appreciated.![This is a diagram of what i am trying to achieve](
The Buddypress plugin allows your users to have a profile and create status posts (Facebook style updates) . It's a very popular and free plugin to use. It appears when going to the Add Plugins page in the Admin area. To add more functionality they're lots of plugins that play well with Buddypress but not all do. I would keep that in mind when adding additional plugins to your site.
stackexchange-wordpress
{ "answer_score": 0, "question_score": 0, "tags": "php, facebook" }
Switch-Case and user_role I am trying to create a page that shows all users with a selection of details. One of those details is the user role it has. For each role I want to display a different string. In order to achieve this is have the following code: function smoelenboek_func(){ $users = get_users('orderby=nicename'); foreach ($users as $user) { switch ($user->roles[0]) { case 'administrator' : echo 'Yes'; case 'member' : echo 'No'; case 'oldmember' : echo 'Maybe'; }; }; }; Now the strange thing that happens is, users with an administrator role get output "YesNoMaybe", a member role gets "NoMaybe" and oldmember gets "Maybe". Am I using the Switch-Case incorrectly? Is there something in the roles array that I'm misinterpreting? Any help is hugely appreciated.
You missed break statement This is how switch case works switch ($i) { case "apple": echo "i is apple"; break; case "bar": echo "i is bar"; break; case "cake": echo "i is cake"; break; }
stackexchange-wordpress
{ "answer_score": 0, "question_score": 0, "tags": "php, user roles, switch" }
Is it a good idea to edit WordPress within Eclipse? A friend and I are building a WordPress website. He has already customised a WordPress theme, and I can view the new site in an Internet explorer and edit it within the WordPress tool. He has sent me the source code. I need to do many modifications, and as a developer, I want to do that with Eclipse instead of the WordPress tool (is it a good idea?) Under Linux, I have already installed Eclipse, PDT, XAMPP, and can run very basic PHP+CSS projects. Does anyone know what are the following configuration steps?
Yes, you absolutely should use a proper code editor like Eclipse instead of the web interface. Another good idea that will save you tons of headaches is to install git and create a local repository for you changes. Commit your changes every time you complete a feature or fix a bug and you'll have a nice way to rollback if you make a mistake somewhere.
stackexchange-wordpress
{ "answer_score": 0, "question_score": 0, "tags": "linux, ide, eclipse" }
Can I use mysql queries to replace query_posts()? I have a template that seems to only accept variables given though `query_posts()`, which appears to work like `get_posts()`, but it's too restricting. So I need to either do it somehow without `query_posts()` or find a way to include filters like > posts that have one or more of several values in this meta value of this meta key with authors who have this value in their meta key inside of it. So far I've been unsuccessfull with both. Is there anything that would help me?
It's not clear what do you mean by template "accepting" variables. `WP_Query` (which `query_posts()`/`get_posts()` are build on top of) is _very_ flexible. In many cases it's not as much being _able_ to do something with it, as having _experience_ using it to achieve results. Typically even when queries cannot be expressed in single set of arguments, it is still very possible to make "compound" queries, by querying partial post sets and further using them in additional queries. That said it _is_ quite possible to use raw SQL. As long as you retrieve records from posts table accurately, you can instance `WP_Post` objects from them. Note that this will skip much of related WP functionality, such as caching, etc.
stackexchange-wordpress
{ "answer_score": 0, "question_score": 0, "tags": "mysql" }
Wordpress Gallery Thumbnail images look blurry I am using the standard WP gallery, and it all looks great on the page until I have images with different sizes. I have resized al the images I could and set them to medium size display and those look great, but some galleries have portrait and landscape images so I cannot resize these to be uniform. My main issue is if I choose thumbnail, the images look really blurry, and if I choose medium the layout is misaligned. Does anyone know of a plugin that can help me?
luckily I found the answer shortly after posting this question. My thumbnail size setting (Settings/Media) was 150 x 150px - cropped. So when I displayed them on my page, desktop size, in a row of 4, the thumbnails were getting stretched to 282 x 282px. I changed it to this new size and used a Rebuild Thumbnail plugin and it looks great now. It scales down nicely so just set it to the maximum size it will be on desktop and it'll display flawlessly. Cheers
stackexchange-wordpress
{ "answer_score": 2, "question_score": 0, "tags": "gallery, thumbnails" }
Is it faster to query records using $wpdb instead of Wp_Query? I mean the speed of query records from database, not the way we render the content gained. More specifically, I just want to query the posts' IDs, my site contains more than 4000 posts (they are custom post type) and I just want to have all their ID.
Yes, custom SQL queries are in essence faster than a custom instance of `WP_Query`. The disadvantage of a custom SQL query is that you are loosing a lot, like object cache, filters and actions, etc, etc, and it is also discouraged to use custom SQL if Wordpress already offers that specific functionality. `WP_Query` does have the option however to only query post ID's ( _which is really fast and very lean_ ) by means of adding and using the `fields` parameter in your query arguments. You can also just use `get_posts` which uses `WP_Query` but does not return the post object but just the array of posts So, you can basically do the following $args = [ 'nopaging' => true, 'fields' => 'ids' // Just get post ID's ]; $q = get_posts( $args ); var_dump( $q );
stackexchange-wordpress
{ "answer_score": 5, "question_score": 2, "tags": "wp query" }
How to change single custom post template by custom taxonomy? Working on a publication (wordpress based) website, having a custom post type "article" with custom taxonomy : language (with only two options: French, English). I made a custom post type template (single-article-french.php) for only French language articles (English ones will be displayed using the single-cpt.php template). How can i make wordpress change automatically the template of my custom post type to single-article-french.php when the language of the article is set to French?
What you would do, is have your default `single-article.php`. This will get called by default because of the WP permalinks and templating system. At the top of your `single-article.php` do the following before your `get_header()` call: <?php $language = get_the_terms( get_the_ID(), 'language' ); if ( ! is_wp_error( $language) && $language && 'French' == $language[0]->name ) { get_template_part( 'single-article-french' ); } else { // english template stuff get_header(); // etc. } That way you will call `single-article-french.php` when the French category is selected.
stackexchange-wordpress
{ "answer_score": 1, "question_score": 0, "tags": "custom post types, custom taxonomy, templates" }
Need help getting a certain value out of a multi dimensional array I'm looking to retrieve a specific meta value for users from the Wordpress types plugin. I know the value is stored in a wpcf-team-experience-member-type. This is a checkbox option and I'd like to retrieve a list of all selected values. Right off the bat if I do something like: var_dump(get_user_meta($user->ID, 'wpcf-team-experience-member-type')) I get something like this: array(1) { [0]=> array(1) { ["wpcf-fields-checkboxes-option-f4fe375f6cad3c44eff97e6e6f16deb2-1"]=> array(1) { [0]=> string(7) "student" } } } wpcf seems to put all of its values inside of an array, and on top of that the checkbox values are stored in an array as well. In this case, the value I'm looking for is 'student' but that array might have multiple values. How would I go about retrieving it? Thank you!
The reason you get the "First" Array is that you don't use the "single" option of the get_user_meta function. Try this: $arr = get_user_meta($user->ID, 'wpcf-team-experience-member-type',true); $options = array(); if(is_array($arr)){ foreach($arr as $key => $value){ foreach($value as $arrvalue){ $options[] = $arrvalue; } } } var_dump($options); This should dump all the options that maybe are in there. Happy Coding, Kuchenundkakao
stackexchange-wordpress
{ "answer_score": 0, "question_score": 0, "tags": "plugins, custom field, user meta, array" }
How does WordPress track that a certain User is Logged-In I am trying to identify the elements that WP uses to track that a user is logged in at any given time. (1) I know WP sets a `COOKIE` for tracking Does anyone know if WordPress also sets a `_SESSION` variable as well? Does anyone know if WordPress records login status in a `DB Table` as well? Is there anything else WP uses to track a user as being logged-in? Thanks
Before core version 4.0 the authentication depended only on cookies. Starting with 4.0 core introduced its own sessions (`WP_Session_Tokens`) to better handle security things. Note that these are **not** PHP sessions, they are implemented purely by WordPress and use user meta as storage. Unfortunately I don't think there is any clear documentation for this feature. From quick search it was discussed and implemented in ticket #20276 Tie nonces and cookies to expirable sessions.
stackexchange-wordpress
{ "answer_score": 3, "question_score": 2, "tags": "login, post status" }
What will be the best caching system for wordpress blog which has more than one million blog posts? I am trying to optimize a wordpress site which has more than one million blog post. I have used ngnix as many of them have recommended as it is one of the best server. I am trying to find what will be the best caching software which will be best for such blog? Thanks in advance
I would suggest using nginx along with varnish. Varnish is a caching mechanism which runs on top of Apache/nginx. You can configure it to purge the cache after a specific time if you have users updating content often. In terms of server configuration, I would recommend Amazon Web Services' EC2. This will allow you to easily scale up as needed. I would not install the database on the EC2 instance, and instead would use Amazon Web Services RDS - which is a load balanced Database server. Varnish Manual WordPress/Varnish Tutorial
stackexchange-wordpress
{ "answer_score": 1, "question_score": 0, "tags": "posts, cache, server load" }
Best method for loading content on mobile - issue with wp_is_mobile I'm trying to prevent loading of extra site menus on mobile. I'd rather not load them at all as opposed to loading them and hiding them with css. I'm starting with this in my header file: ` <?php if(wp_is_mobile()) : ?> <?php /*?>Don't load full menus on mobile<?php */?> <?php else : ?> //Code for additional menus goes here <?php endif; ?> ` It works, but I pushed this change on Friday - and our site is timing out this week. It could be totally unrelated, but I found a statement in the codex that says " It also should not be used for themes." - < Does this mean I can't use the function in this way? I found several references / examples like the logic I used. If not in a theme, how can I use it? Bottom line... what is the best way to prevent **loading** of content on mobile?
Yes, you shouldn't use it in your theme. It's used in WP core on administration side for adding touch scripts, mobile button etc. It's very dumb, it just detects User Agent string which can anybody change. And the biggest why not to use it is that you can have a trouble if you use it with a cache plugin because it can show mobile version when desktop version should showed.. It's safe to use it in backend because all caching plugins caching only frontend not backend. I think that the safest method would be input all content and show/hide whatever you want via media queries.
stackexchange-wordpress
{ "answer_score": 3, "question_score": 0, "tags": "mobile, responsive" }
What's hook to use immediately after a user is authentcated Does anyone know the `add_action()` hook to use immediately after a user is successfully authenticated. **Hook Test based on @mmm's answer** I ran this test from my `mu-plugins.php` file: function check_for_superAdmin() { if ( is_super_admin() ) { echo 'I\'m a Super Admin !'; exit; } } add_action( 'wp_login', 'check_for_superAdmin' ); the `check_for_superAdmin()` function works but the `is_super_admin()` function does not. I may need to pass a parameter in there. Checking....
juste before testing login and password, you have the action `wp_authenticate`: < juste after test and only if logging is successful, the action `wp_login`: < and after logging, you can also modify the URL with the filter `login_redirect`: <
stackexchange-wordpress
{ "answer_score": 2, "question_score": 1, "tags": "hooks, actions, authentication" }
the_post_thumbnail('medium') setting some images width=1 height=1 I have a created a custom post type and gave it a field of image which can contain a gallery. When I'm inside `content.php` I can call up all available data such as title, postmeta and such just fine but some of the post's images are given `width=1 height=1` in the `<img>` if I use `the_post_thumbnail('medium')` or `the_post_thumbnail(array(300,300))`. Im not sure if there is a database issue or a fault with the image that I'm unaware of.
It's only a guess, but it's also most probable cause... When you upload an image to WP, some metadata is generated and stored in database. This metadata contains such info like name, path and size of the image (to be more precise - paths and sizes of all created images based on uploaded one). And... This metadata is stored as serialized array. When the metadata is corrupted (so WP is not able to unserialize it), it can cause images with size 1x1 (WP doesn't know what is the size of given image). **What should you do in such case?** It's easy to correct this. All you need to do is to regenerate metadata for these images. (There are many plugins which will help you with this - look for "regenerate thumbnails" or "rebuild" thumbnails").
stackexchange-wordpress
{ "answer_score": 2, "question_score": 0, "tags": "images, post thumbnails" }
Show posts by author of membership level (Paid Membership Pro) I am currently listing posts based on user role, with the following query: $ids = get_users( array('role' => 'author' ,'fields' => 'ID') ); $args = array( 'author' => implode(',', $ids), 'orderby' => 'date', 'order' => 'ASC', ); Would it be possible to also limit the posts based on the membership level of the author using Paid Membership Pro? The plugin has the following hook to check user level: if(pmpro_hasMembershipLevel($level_id)) But I'm not sure how to incorporate it into the above query (if possible)?
$ids = get_users( array('role' => 'author' ,'fields' => 'ID') ); $contr_limit = count($ids); for($cntr=0; $cntr < $contr_limit; $cntr++){ if( pmpro_hasMembershipLevel($level_id, $ids[$cntr] ) !== true ){ unset($ids[$cntr]); } } $args = array( 'author' => implode(',', $ids), 'orderby' => 'date', 'order' => 'ASC', );
stackexchange-wordpress
{ "answer_score": 1, "question_score": 0, "tags": "posts, wp query, user roles" }
Enqueue styles through the wp_enqueue_style function vs link tag inside header.php I read that I should insert my `style.css` file in my theme through the `wp_enqueue_style()` function because it's not a good solution to add that file through a link tag in the html of the `header.php` file. Could you explain me the reasons?
Three good reasons to use the enqueue functions over hard coding are to eliminate duplication, avoiding library conflicts, and handling dependencies: * **Duplication:** If, for example, you hard code a link to jQuery, and then install a plugin which also enqueues the jQuery library, you're site will be loading the same library twice, which will affect the page load speed, amongst other things. * **Library conflicts:** Much like duplication, but the plugin may be loading a different version of jQuery, which results in your page trying to load two conflicting versions, which could cause serious page problems. * **Handling dependencies:** If you create a custom script which relies on a javascript library, you can add the dependency as a parameter of the enqueue function, which will ensure that the required library is loaded before the custom script. Easy enough to do with hard coding, but easier to keep track of with `wp_enqueue_style()`. Further reading here: <
stackexchange-wordpress
{ "answer_score": 5, "question_score": 3, "tags": "wp enqueue style" }
Relationship field search not retriving posts in admin I have a site with 5000+ posts and a theme option page with a relationship field on it. The infinite scroll and Taxonomy filter function of the relationship field works, but the search doesn't. Obviously with this many posts that's a deal breaker... I can see it is making an ajax request via admin-ajax.php, but nothing is being returned. I have checked my error logs and there is nothing in there. How do I diagnose / fix this? I'm guessing something is timing out? It runs ok in MAMP, but not my live server. I have tried modifying the php memory_limit, max_execution_time, and WP memory limits in wp-config.php. I've run out of ideas!
Turns out there is currently a conflict between Advanced Custom Fields Pro (5.2.8) and Relevanssi Premium (1.13.3) plugins. If you enable the 'Use search in admin' function in Relevanssi then the problem described above appears. ACF support put the 'blame' in the Relevanssi plugin. I'm awaiting a reply from the developer if there is a work-around or solution. For now I have disabled Relevanssi search in the admin area and ACf now works as expected.
stackexchange-wordpress
{ "answer_score": 0, "question_score": 0, "tags": "advanced custom fields" }
Wordpress doesn't display accents after migration **I know this is a common question** , but I've searched a lot and only experience this since a few months, without knowing what's causing this issue of course, maybe since a Wordpress update. This is now happening each time I move a WP installation to another server. My procedure : * Export DB from dev site. * Search & Replace old URL by new URL. * Import DB in new site. **Before answering me I messed with the encoding sets** , please consider this : * In my fresh new DB, special chars are well displayed (french - see acccents) : ![PHPMyAdmin]( * In front-end, accents fail : ![enter image description here]( * In WP Dashboard, page titles don't even display, although they're displayed in the menu (cf. previous pic) ('pas de titre' means 'no title') ![enter image description here]( What should I do to migrate WP installation properly ???
**Alleluia...** After multiple trials (like converting my tables to utf8_unicode_ci -- didnt work), here's the only successful fix I found : define('DB_CHARSET', 'utf8'); In `wp-config.php`, replace `utf8mb4` by `utf8`.
stackexchange-wordpress
{ "answer_score": 2, "question_score": 0, "tags": "mysql, encoding" }
Missing content on author archive page I got problem when I deal with the 'author archives' pages. Initially I used default 'archives.php' from my theme. Then I add a 'author.php' page, tested on my local machine, it was ok to show the archives. After I uploaded the file to my server, the content just can't show up. I have installed Yoast SEO plugin and I knew it offers a 'disable author archives' function. I'm sure I've unchecked it. The code itself could fetch the right author name in the title of author archive page, while the content are gone. So I can't To those who may concern, here's the archive page of my site: < Thank you for your patience.
Fixed. I used code: <div class="panel callout radius"> <?php echo get_avatar( get_the_author_meta( 'user_email' ), '96' ); ?> <div class="right"> <a href=" the_author_meta( 'twitter' ); ?>" target="_blank"><i class="fi-social-twitter size-24"></i></a>&nbsp; <a href="<?php the_author_meta( 'facebook' ); ?>" target="_blank"><i class="fi-social-facebook size-24"></i></a>&nbsp; <a href="mailto:<?php the_author_meta( 'email' ); ?>"><i class="fi-mail size-24"></i></a> Then I found out this function could only be used in single blog page (single.php). So I followed official guide and called a curauth like: <?php get_header(); global $curauth; $curauth = (isset($_GET['author_name'])) ? get_user_by('slug', $author_name) : get_userdata(intval($author)); ?> Then it worked now. Thanks.
stackexchange-wordpress
{ "answer_score": 0, "question_score": 0, "tags": "archives, author, plugin wp seo yoast, author template" }
Authorization link broken when migrating from Blogger to Wordpress I recently purchased a domain and hosting and I'm running a WordPress site on a subdomain. I want to transfer a small blog of mine which is hosted on Blogger. I've seen instructions such as these that walk you through the steps, but when I get to this page: ![Authorization page]( The `Authorize` link leads me a broken Google support page that looks like this: ![enter image description here]( Does this mean that automatic migration from Blogger to WordPress is no longer supported? Does this link simply need to be updated? Are there other options I should consider to transfer my blog?
This plugin is obsolete as of August 2015. According to this thread, a new version is being worked on. Until then, I have found success importing Blogger using this alternative plugin.
stackexchange-wordpress
{ "answer_score": 0, "question_score": 0, "tags": "migration, blogger" }
Best action hook to create custom post and assign taxonomy terms to it on plugin activation? When I install the plugin, I want to create 10 CPTs of a particular type, which I define in the `init` action hook, and want to assign 10 terms of a custom taxonomy, which too is defined in an `init` callback. I tried doing it on `register_activation_hook`, but the CPT's terms are not set. Is there a way to achieve this?
According to the docs, I needed to set the terms using post ID. So after every insert, I used the ID to set the terms < Someone might find this useful.
stackexchange-wordpress
{ "answer_score": 0, "question_score": 2, "tags": "custom post types, plugins, custom taxonomy, init" }
How to check if a post "does not have term" in conditional statement? We know that we can check if the particular post has a term by using this code: has_term('term', 'taxonomy', $post->ID )) { I was wondering if there is a code to check if a particular post does not have a particular term. Thanks.
if ( !has_term('term', 'taxonomy', $post->ID )) { Use the NOT (`!`) operator
stackexchange-wordpress
{ "answer_score": 8, "question_score": 1, "tags": "wp query, conditional tags" }
Disable wp_is_mobile() I have a mobile version for my web-site and i used wp_is_mobile(). I will have a button on mobile devices which lets users to switch between the mobile and original versions. Is there a way to disable wp_is_mobile()? Or i can some how trick php to think that the mobile is not a mobile. Thank you for your time. Note: I don't want to use display: none or other css. I need the content to not appear on mobile version in any ways.
Did it other way. I created a new theme for a mobile device and am using a plugin to switch between them.
stackexchange-wordpress
{ "answer_score": 0, "question_score": 0, "tags": "functions, mobile" }
add_filter to wp_nav_menu_objects having no impact I'm attempting to add thumbnails to navigation items as per this question. However, after adding the sample code to the top of my functions.php file nothing happens. I've whittled the code down in an attempt to get anything to happen. The code is now this: add_filter('wp_nav_menu_objects', 'ad_filter_menu', 10, 2); function ad_filter_menu($sorted_menu_objects, $args) { return ''; } Still nothing is happening. The menu appears absolutely normally. Heres the code thats generating the menu in header.php: <?php wp_nav_menu( array( 'theme_location' => 'main-menu' ) ); ?> What am I missing?
**First:** Your `ad_filter_menu` is a _filter_ function: it filters/manipulates `$sorted_menu_objects` That's why you always have to return the `$sorted_menu_objects`, and `return '';` won't work. **Second:** A better way to achieve the desired behavior (adding thumbnails to navigation) is to extend the `Walker_Nav_Menu` class There are several guides and templates out there that fix this for you, see for example this previous question
stackexchange-wordpress
{ "answer_score": 1, "question_score": 0, "tags": "filters" }
How to set default editor tab I'd like to have always open the Text tab in editor in administration instead the HTML tab. Is it possible?
It's easier then you thought! Just add this code to the functions.php file in your theme. function prefix_set_default_editor() { return 'text'; } add_filter( 'wp_default_editor', 'prefix_set_default_editor' );
stackexchange-wordpress
{ "answer_score": 1, "question_score": 1, "tags": "admin, editor" }
How do I limit the number of posts displayed to one? I have searched Stack and the codex but can't find a simple solution for limiting the number of posts returned to one using the following: <?php query_posts('cat=24'); ?> <?php while (have_posts()) : the_post(); ?> <?php the_field('alert'); ?> <?php endwhile;?>
<?php query_posts('cat=24&posts_per_page=1'); ?> But using query_posts is a **very bad idea**. This is straigt from the Codex: For general post queries, use WP_Query or get_posts. It is **strongly** recommended that you use the pre_get_posts filter instead, and alter the main query by checking is_main_query.
stackexchange-wordpress
{ "answer_score": 1, "question_score": 0, "tags": "posts" }
Installing google analytics code on wordpress blog There are many ways suggested on the internet to install google analytics code on wordpress blog and I would like to clear my doubts. When I copy the analytics code to the footer.php * Will this be available for all pages & post? * after theme update, will the custom analytics code still remain What is the advantage of using google tag manager? Which is the best way and why?
Since your question is about installing the google analytics code in Wordpress, I will highly recommend you to install the **UA-XXXXXX-X tracking code** before the closing head tag "`</head>`". Just edit the theme header.php file. You don't need to create a child theme unless you are using someone else's theme that could potentialy be updated or ask you for an update from which your tracking code will be deleted.
stackexchange-wordpress
{ "answer_score": 2, "question_score": 2, "tags": "google analytics" }
Adding content before the loop in category pages I am creating a plugin and I want to show all sub category list in the top of every category page. I had created a function and call "`wp_list_categories`" in that function. The problem is when I call that via add_filter('the_content', 'myfunction'); List of all sub category is return successfully. Before every post and i just want to show it in top before first post. And when call same function via add_filter('wp_list_categories', 'myfunction'); Nothing return and show blank page
`loop_start` should be a good option. `loop_start` executes before the loop displays the first post ## EXAMPLE: add_action( 'loop_start', function ( $q ) { if ( $q->is_main_query() // Do this only for the main query && $q->is_category() // Only target category pages ) { // Add your code here } });
stackexchange-wordpress
{ "answer_score": 3, "question_score": 1, "tags": "plugins, plugin development" }
Function not saving unchecked checkbox I'm trying to save custom option for taxonomies in `wp_options`. The following function saves the post id in array if checkbox is checked but when I uncheck the checkbox it doesn't removes term id from wp_options. function wpfs_save_tax($term_id) { $featured_tax = get_option('_featured_tax'); if(empty($featured_tax) ) { $featured_tax = array(); } if (isset($_POST['wpfs_tax'])) { if(!in_array($term_id, $featured_tax) ) { $featured_tax[] = $term_id; } } else { if(in_array($term_id, $featured_tax) ) { unset($featured_tax[$term_id]); } } //isset update_option('_featured_tax', $featured_tax); } Please review my code.
Strictly by what I see in your code: you are trying to `unset` incorrectly, `unset` works by means of an array key and you are using `$term_id` which is a value. You need to find the index in the array for that `$term_id`: function wpfs_save_tax( $term_id ) { $featured_tax = get_option( '_featured_tax' ); if ( empty( $featured_tax ) ) { $featured_tax = array(); } if ( isset( $_POST['wpfs_tax'] ) ) { if ( ! in_array( $term_id, $featured_tax ) ) { $featured_tax[] = $term_id; } } else { if ( in_array( $term_id, $featured_tax ) ) { unset( $featured_tax[array_search( $term_id, $featured_tax )] ); } } update_option( '_featured_tax', $featured_tax ); }
stackexchange-wordpress
{ "answer_score": 1, "question_score": 0, "tags": "functions" }
How Child Themes Directory works for plugins? I am working on a Wordpress installation, that another developer used to do. I have an issue since he was working only with Child Theme Directory whereas I didn't. What I want to do, is to edit the source code of a plugin. I read the documentation but I am not sure if there is something there about it. Will I just copy paste the file in the child directory and edit it or I must mention somewhere that I have edited this file and it should load it from the child directory? The child directory has already created with many files, previously from the other dev.
Plugins are not kept in the theme directory. It doesn't matter if you are using a child theme or not. Maybe you're asking a different question? Are you asking how to make a "child-plugin"? Plugins are generally kept here: wp-content/plugins. Whereas child themes and themes are kept here: wp-content/themes As far as "child-plugins" there is not an official way to do it, but I think this article sums up pretty nicely what you could do to accomplish that, < .
stackexchange-wordpress
{ "answer_score": 3, "question_score": 0, "tags": "child theme" }
woocommerce single product page hook not working I have written a function which will display a date picker and a select box. I want this function output to be displayed on woocommerce single product page. So I assigned my function to a hook woocommerce_after_single_product_summary and I am not seeing any fields appearing in the product page. Can anyone please help?. so far per my knowledge the function is working fine as I have tested it using its shortcode in a page. Below is the hook I am trying to add, timeslot_display is my function also I have added a screenshot of my function output. add_action('woocommerce_after_single_product_summary', 'timeslot_display') ![enter image description here](
Thanks WisdmLabs. I traced it finally after the discussion. The changes in product page are appearing now. Below is the mistake I have done.I am posting this as it might help others with similar problems. In my plugin I am calling file B in file A using require_once. I have placed my function timeslot_display() and hook calling line in file B which did not give any results. When I copied the entire code of file B to file A, then I am able to see the changes in product page. Not sure why this happened but it worked.
stackexchange-wordpress
{ "answer_score": 0, "question_score": 0, "tags": "plugin development, hooks, woocommerce offtopic" }
How to check plugins for malicious code? Our new hosting company ran a security check on our installation and I was very surprised to hear that a premium plugin we had purchased (Easy Media Gallery Pro) contained malicious code. (It may just be coincidental, but our site was hacked around the time we upgraded to the Pro version of that plugin.) Anyway, I would like to know if there are any reliable utilities out there than can perform an reliable, independent security check on a plugin **before** I install it on my site??
There are several options/plugins to do that but nothing can provide you with 100% security. Following good practices, daily/weekly backups and using themes/plugins that follow good code practices will usually help you to stay away of troubles. But again nothing will give you 100% security. As for plugins you can try several that will give you a little peace of mind: * Wordfence Security * iThemes Security (formerly Better WP Security) * All In One WP Security & Firewall I've worked mainly with Wordfence Security since most of the plugins I use come from the official WP repository and it has some neat settings that allow you to compare your theme's/plugins' code against changes directly with the theme's/plugins' repo and scan the code for potential issues. **But again this is not a 100% solution.**
stackexchange-wordpress
{ "answer_score": 3, "question_score": 3, "tags": "plugins, security" }
How to delete woo commerce order pragmatically? I am trying to delete an order from database i was tried using bellow function but this is not working.can any body tell me how to delete an order from db using order id. <?php wc_delete_order_item( absint( $order_id ) ); ?>
Orders are just regular posts: wp_delete_post($order_id,true);
stackexchange-wordpress
{ "answer_score": 10, "question_score": 3, "tags": "woocommerce offtopic" }
Adding Page URL to the Pages Admin Table I want to add the Page URL as a custom column to the Pages admin table. Here is where I am at with the code. Code is in the theme's functions.php. function lrh_modify_page_table( $column ) { $column['lrh_url'] = 'URL'; return $column; } add_filter( 'manage_pages_columns', 'lrh_modify_page_table' ); function lrh_modify_page_table_row( $column_name, $post_id ) { $url = get_permalink( $post_id, true); switch ($column_name) { case 'lrh_url' : echo $url; break; default: } } add_action( 'manage_pages_custom_column', 'lrh_modify_page_table_row', 10, 2 ); Right now it is returning the url as < How do I get it to return the actual URL of the page?
Remove the true parameter in the get_permalink function $url = get_permalink( $post_id );
stackexchange-wordpress
{ "answer_score": 0, "question_score": 1, "tags": "pages, admin, columns, screen columns" }