INSTRUCTION
stringlengths
11
999
RESPONSE
stringlengths
0
999
SOURCE
stringlengths
16
38
METADATA
dict
Gutenberg MediaUpload component with default gallery functionality? I have seen a few tutorials around utilizing the MediaUpload component from below. < But none of them demonstrate it with the default gallery functionality that is common pre-Gutenberg. For example the ability to select multiple images and then be taken to a second screen where you can order and caption them. See attachments if further info is needed. There is the **multiple** attribute which can be set to "true" or "add" but it doesn't toggle the second screen for ordering the items or captioning them. ![1st Screen]( ![2nd Screen](
It isn't documented but if we take a look to the gallery block, we see it passes an extra prop to the MediaUpload component. Try to pass `gallery` as well as `multiple` to the component.
stackexchange-wordpress
{ "answer_score": 1, "question_score": 1, "tags": "gallery, block editor" }
Comments are in database, don't show up in WordPress backend or frontend I am in the process of rescuing the content from a WordPress site with a bloated/damaged database. Everything has gone according to plan except for the comments. I can see that the 4000+ comments are indeed in the database's `wp_comments` table, and I verified that the IDs of the associated posts are correct, but none of them show up in the WordPress admin area or the front-end. I haven't been able to find where the issue lies. Maybe someone in the community has an idea for a possible fix? Thanks. Edit: to clarify, I already moved the content to a new database, the issue happens on the new WordPress installation. The comments were imported to the database when importing the posts through the export/import tool.
Ok, so after going over the database structure, I realized that for some reason all comments status on the table comment_approved had been set to post-trashed. Changing the value of that column to '1' made it all reappear.
stackexchange-wordpress
{ "answer_score": 0, "question_score": 0, "tags": "posts, database, comments" }
What is debug.log.old? It seems to take up a lot of space what is debug.log.old (please see attached image). It seems to take up a lot of space. Is it necessary to delete it? Or should I leave it alone? Thanks![screenshot](
It is not necessary to delete it but if you want to save your space then you can delete it. Actually when we turn on the debugger then debug.log file created. It contains the warnings and errors of the code. May be your development team have renamed it with debug.log.old. You can delete it or not its all depend upon you.
stackexchange-wordpress
{ "answer_score": 1, "question_score": 0, "tags": "debug" }
Include a PHP file inside an array I'm trying to add a custom PHP script inside of the nav menu (before the closing ) and struggling. Code here: <?php wp_nav_menu(array( 'theme_location' => 'menu-1', 'menu_id' => 'primary-menu', 'items_wrap' => '<ul id="%1$s" class="%2$s">%3$s<div class="my-div">' . $addCats . '</div></ul>' )); $addCats = require_once('custom_menu_addon.php'); ?> The above code includes the file outside of the new added to the menu: ![enter image description here]( Any recommendations for getting this to print inside the div? Am I using the wrong command to pull the file contents there? Thank you in advance for your help and guidance! <3
Please Use Below code <?php $addcats = array(); ob_start(); require 'custom_menu_addon.php'; $addCats = ob_get_clean(); wp_nav_menu(array( 'theme_location' => 'menu-1', 'menu_id' => 'primary-menu', 'items_wrap' => '<ul id="%1$s" class="%2$s">%3$s<div class="my-div">' . $addCats . '</div></ul>' )); I've edited this answer after some research into the usage of this object array and put it in context with my code, works well on the site :)
stackexchange-wordpress
{ "answer_score": -1, "question_score": 1, "tags": "php" }
Custom Archive Template for Multiple Categories I want to create a custom archive template for two post categories. One of my categories is events, and the other one is courses (I have more). I already have a custom template for events (category-event.php), but I want to create another one to list both events and courses, but not include any other categories. The layout will be more or less the same as the category-event.php template. How can I do this?
The simplest way I can think of would be to have the two categories you want to display together grouped under a parent category. Parent Category |----Child Category A |----Child Category B The file category-parent-category.php would by default show posts from both. The file category-child-category-a.php would only show from a. The file category-child-category-b.php would only show from b. The file category.php would show from all categories. Would that do what you want?
stackexchange-wordpress
{ "answer_score": 0, "question_score": 0, "tags": "categories, templates, template hierarchy" }
How to check if a post has at least 2 terms from a custom taxonomy attached? I have a custom taxonomy with several terms. I need to check if the post has more than 1 of these terms. How can it be done?
get_the_terms( int|object $post, string $taxonomy ). Use the above function to get the terms of the taxonomy. It will return the array of terms associated with the post. Then you can use the php function $count = count( $array ). it will return the count of the terms. After getting the count use the if statement if( $count > 1) { //do what you want }.
stackexchange-wordpress
{ "answer_score": 1, "question_score": 0, "tags": "custom taxonomy, terms" }
Integrate Gutenberg as a Standalone App I'm thinking about integrating the new awesome WordPress block editor (Gutenberg) outside of its environment (WordPress core), so is there any way to get just the text editor code and use it for example in another CMS or framework or just a simple HTML page?
Yes, You can use Gutenberg as a standalone app or CMS agnostic app. Drupal using Gutenberg as a npm module and then integrating in their own CMS. Drupal Gutenberg is decoupling Gutenberg from WordPress and using as JS editor Gutenberg JS. This way, developers can build block for Gutenberg and port it to two different CMS.
stackexchange-wordpress
{ "answer_score": 7, "question_score": 8, "tags": "block editor" }
Number of Style for Image Added into Post When adding an image through the GUI, an `HTML` element is created: <img src=" alt="leaf graphic" title="leaf graphic" class="alignright size-medium wp-image-3109" height="25" width="30"/> A sequential `3109` and a style name `wp-image-3109` (?) is generated. Besides, I cannot find it in any table in the DB (`wp_posts`, `wp_postmeta` or any other table). How the next ID must be generated? Is there a WP PHP function returning it? Thanks in advance.
I’m not sure if I understand your question correctly, but... In WP any attachment is a post (of attachment type). So 3109 is ID of that post. This means, that if you’ll take a look at wp_posts table, then you should find that post and there should be some additional info stored as meta fields in wp_postmeta table (for example sizes of all generated images are stored as meta). So the ID of next uploaded image will be the next value of ID column in wp_posts table.
stackexchange-wordpress
{ "answer_score": 1, "question_score": 0, "tags": "images" }
WordPress 5 WP REST routes - No errors I'm using WP JSON to return JSON for certain routes. Prior to WordPress 5, WP JSON would return PHP errors in the response, e.g. `Notice:xxx` or `Warning:xxx` when a PHP error was encountered. Since I upgraded to WordPress 5, such errors are supressed/ skipped and JSON is returned. Fatal errors return a 500 as expected. I cannot find any documentation identifying why these errors are not being returned. And Google doesn't seem to be shedding any light. Does anybody know what's going on? Also, if it's "toggleable", does anyone know how to "turn errors on"? PHP outputs errors to screen as usual elsewhere in WordPress.
REST API should always return JSON, so it’s output can be parsed as such. If it’ll return something that is not correct JSON, then your JS scripts may stop working. This is why there should be no errors printed in these requests - such messages break JSON response and make it hard to parse. And there was some code that was trying to prevent such messages from occurring, but it wasn’t working properly. This was fixed in 5.0 in bug #44534. You can always add this code to your method, id you're really (really really really) sure, what you're doing: if ( true === WP_DEBUG ) @ini_set( 'display_errors', 1 ); PS. You should never display errors on production server - it’s compromising security of your site. Always use files as logging method. (It’s also easier)
stackexchange-wordpress
{ "answer_score": 1, "question_score": 1, "tags": "php, errors, rest api" }
How to align full div I want to align this **scrolling events** on the slider left to right but it's not working. Can anyone tell me the exact way to align it at the **right** side on the slider image using custom css? .un-post-scroller { position: absolute; float: right; }
The main issue you are running into is that you are targeting the wrong element. The parent of .un-post-scoller is what has a limited width aligned to the left, so you won't escape that easily. Instead, target its parent. Unfortunately there is not a particularly clean candidate here since the parent is a generic grid system class (col-md-5). Usually you want to use the grid system's class to move things over -- in the case of Bootstrap, that would be offset-md-7 (or slightly different depending on your version and which grid system you use). That requires modifying the actual HTML. Since you asked specifically for how to do it with CSS, you might try something like: .header-overlay-scroller .col-md-5 { float: right; } The header-overlay-scroller is just there so that not **all** .col-md-5 classes are targeted.
stackexchange-wordpress
{ "answer_score": 0, "question_score": 1, "tags": "css" }
Get count of custom post tags I am trying to get the count of custom post tags `gd_place_tags`. But I just get the value "0" back. function tag_count( $tagatts ) { $tagatts = get_terms( array('taxonomy' => 'gd_place_tags','hide_empty' => false)); return ( isset( $tagatts->count ) ) ? $tagatts->count : 0; } add_shortcode( 'tag_count', 'tag_count' ); And yes, I'm not a developer but I am trying to learn! :-)
why don't you try: function tag_count( $tagatts ) { $tagatts = get_terms( array( 'taxonomy' => 'gd_place_tags', 'hide_empty' => false, ) ); $tagatts_count = count ( $tagatts ); return $tagatts_count; } add_shortcode( 'tag_count', 'tag_count' ); it should actually return the term count. I'm just using php for Count instead of a wordpress function.
stackexchange-wordpress
{ "answer_score": 0, "question_score": 1, "tags": "tags, count" }
require/include php file in add_menu() I'm creating a custom WP Admin Bar menu item with custom HTML inside the dropdowns. Referring to this: < the HTML i want to use is quite extensive so I created a separate php file for that HTML. Then I'm trying to include that PHP file inside the menu item, but it's not printing/echoing properly. Right now, all the shows inside the menu item is a 1, and the content is getting printed later on in the DOM of the page. Here's the code I have: $admin_bar->add_menu( array( 'id' => 'dh_row_layouts-content', 'parent' => 'dh_row_layouts', 'meta' => array( 'class' => 'dh_hack', 'html' => include('docs/row_layouts.php'), ), ) ); Any ideas?
You can turn on output buffering, `include` (and evaluate) the PHP file, and save the output (of the evaluated code) in a variable, like so: ob_start(); include 'docs/row_layouts.php'; $html = ob_get_clean(); Then just use `'html' => $html` in the `meta` array when you call the `$admin_bar->add_menu()`. Or if you _don't_ need to evaluate any PHP code in the file, you could use `file_get_contents()`: 'html' => file_get_contents( 'docs/row_layouts.php' ) And you may need to or better use a full absolute path.
stackexchange-wordpress
{ "answer_score": 0, "question_score": 0, "tags": "admin, admin menu, admin bar" }
Detect if REST API is running Many times I have code and I want to make sure it only runs in a rest api context, or it never runs in a rest context. I know there are some hooks, but is there a function similar to `wp_is_doing_cron`?
I would use : if ( defined( 'REST_REQUEST' ) && REST_REQUEST ) {...} Source: < If you take a look to this source code on you will notice the constant is defined before processing anything, I would check for it instead of calling the mentioned function `wp_is_json_request()` Why? if headers were not set when you do the check, it will return false, here is a real example reported for a GET request: <
stackexchange-wordpress
{ "answer_score": 4, "question_score": 1, "tags": "rest api" }
Plugin keeps saying needs to be updated and it's in a constant loop I have a plugin that is on "Version 1.0" When I update it (as indicated within my dashboard) it revers back to the same message. The plugin is at "1.0" and the "update" is also at "1.0" so clearly there's an error or mismatch. Question is: how do I remove the loop? Thanks!
I'd just deactivate then uninstall then install again. Depending on the plugin, you might lose some customization or settings. But a lot of plugins don't remove anything they stored in the wp-options table (normally where plugin options are stored), so you may not lose any settings. But I'd go to the plugins' support page. That's the best place for plugin support. **Added** Since the plugin support route didn't work, perhaps you can 'force' the plugin not to be checked for updates. This question has some ways to do it: < with this code (adjust for the plugin's folder): add_filter('site_transient_update_plugins', 'remove_update_notification'); function remove_update_notification($value) { unset($value->response[ plugin_basename(__FILE__) ]); return $value; } Put that in the site's function.php (optimally in a Child Theme), or in a (possibly private) plugin of your own.
stackexchange-wordpress
{ "answer_score": -1, "question_score": 0, "tags": "plugins, plugin development" }
Give wp-admin access for shop managers I setup some new roles for shop-managers in my woocommerce shop but i have no idea how to enable access to wordpress dashboard. I created new options for it but i cant find anything to enable the wp-admin access. thanks
Logged in users have access to wp-admin by default, so you must have some other settings in a plugin or theme that is not allowing access. Do you have any membership or user manager plugins installed? If so, check the setting for allowing/disallowing wp-admin access.
stackexchange-wordpress
{ "answer_score": 0, "question_score": 0, "tags": "wp admin, user roles" }
<meta> in source code but I can't find it in files or plugins I've got someone verified in my Google Search Console for our site and it's using a meta tag in the head. I've checked header.php in the theme and the child and it's not there. I've double checked wp_head (includes/general). and it's not there either. I found some plugins to add scripts to the head but it isn't there. I checked Google Tag Manager we're not injecting anything there. Can anyone think of anywhere I haven't looked where this meta tag might be coming from? I've checked the Google Analytics and Tag Managers plugins the owner has installed and it's neither of them (at least not in the settings)
It could be a lot of things, and as RiddleMeThis says, a DB search would shine light on the situation. However, in my experience, most cases of unexpected meta are generated with Yoast. For your specific case, here is how to link Google Search Console with Yoast - it might help you remove the unwanted meta: < Let me know if it doesn't work, and we can dive into searching the DB!
stackexchange-wordpress
{ "answer_score": 1, "question_score": 0, "tags": "plugins, admin" }
How can i delete options on plugin uninstallation? I want to delete option from database when plugin uninstall. It's name is `test_option`. I am using this code but doesn't work. Where is problem? function test_delete() { if( !current_user_can( 'activate_plugins' ) ) return; check_admin_referer( 'bulk-plugins' ); if( __FILE__ != WP_UNINSTALL_PLUGIN ) return; delete_option( 'test_option' ); } register_uninstall_hook( __FILE__, 'test_delete' );
This will give you the option to register your unistall hook during plugin activation. function myplugin_activation_callback(){ register_uninstall_hook( __FILE__, 'myplugin_uninstall_callback' ); } register_activation_hook( __FILE__, 'myplugin_activation_callback' ); function myplugin_uninstall_callback(){ //Perform your uninstall operations here delete_option('test_option'); } However, the simplest way is to use an `uninstall.php` file with the following codes: if (!defined('WP_UNINSTALL_PLUGIN')) { die; } //Perform your uninstall operations here delete_option('test_option'); It's not recommended to use both at the same time.
stackexchange-wordpress
{ "answer_score": 2, "question_score": 0, "tags": "plugins" }
WordPress wp_nav_menu with a nav tag I'm thinking about wrapping the `wp_nav_menu` with a nav tag instead of a div tag. I've read at the WordPress codex that the container argument is only for using `ul` or `div`. Do you guys know a way how to display the navigation in a nav tag so that the output looks like this: <nav class="menu-header-menue-container"> <ul id="menu-header-menue" class="menu"> <li id="menu-item-86" class="menu-item menu-item-type-custom menu-item-object-custom menu-item-86"><a href="home"></a></li> </ul> </nav>
You were really close. There is `container` argument for `wp_nav_menu`: > **'container'** (string) Whether to wrap the ul, and what to wrap it with. Default 'div'. Its default value is 'div', which means, that the `ul` will be wrapped with `div` tag. You can change it to `false` \- `ul` won't get wrapped at all in such case. But you can also change it to `nav` \- and that is what you're looking.
stackexchange-wordpress
{ "answer_score": 2, "question_score": 2, "tags": "menus, navigation" }
Page-parent field not appearing in editor The drop-down of page parents doesn't appear in some sites as of upgrading to WordPress 5.0.+
It seems the problem is with shortcodes, specifically if they echo any content - which of course they shouldn't. We had shortcodes registered to programmatically generate content on some pages on the front-end of the site but the functions the short-codes call appear to get called from the backend, even when creating a new page that doesn't call the shortcode, breaking the lazy-loading of that field. As a quick fix I wrapped the function's content in a `is_page()` test and that seems to fix the problem: `add_shortcode('my_shortcode_str', 'my_shortcode_fx'); function my_shortcode_fx() { if (is_page()) { /* only render on front-end, otherwise kills lazy load of page parent field in WP edit screen */ $content = /*something*/; return $content; } // ends is_page } ` The proper solution is to make sure the shortcode's function only returns the content and doesn't output anything itself.
stackexchange-wordpress
{ "answer_score": -1, "question_score": -1, "tags": "pages, page attributes, page specific settings" }
Can't publish post using ajax I have an issue, i create three input in frontend(title, body, and name) I process the value using wp-ajax, and in my ajax function I use wp_insert_post to create a new post. if I put 'post_status =>' publish' in my wp_insert_post, I get error 500 in ajax-admin, but if I remove it my code is fine. I want create a post with publish status. I also already put wp_publish_post after wp_insert_post in same ajax-function. but also getting 500 error. Is there any solution for this issue?
To those who are experiencing the same issue, there are few steps to take to determine the culprit. 1. Create posts manually in the WP Dashboard area (set it to future) 2. .. and manually publish (look for the error in the log). 3. step 1 and trash the post, in the Trash, try reverting that post (this generally create a log, and a log is all we need in this case). 4. Check for any plugin which filters the post publish. Hope this helps
stackexchange-wordpress
{ "answer_score": 1, "question_score": 1, "tags": "ajax, wp insert post" }
restore_current_blog required after switch_to_blog, if I use that in a function? class Basics { public function build_frontend_post_form( $blog_object ) { switch_to_blog( $blog_object->blog_id ); if( !( current_user_can( 'administrator' ) and current_user_can( 'publish_posts' ) ) ) { restore_current_blog(); return false; } restore_current_blog(); #DO STUFF } } In the exclusion (and anyway if not necessary for my logic) I need to use it restore_current_blog, or enough the return false? So In this case the base blog will be restoring after the function or not?
`switch_to_blog` changes values of global variables (as you can see here: < It doesn’t matter if you call it in function or not - these variables will get changed. So yes - you always have to call `restore_current_blog` when you’ve done all you wanted with the switched blog. Otherwise these variables will stay changed (so `wpdb` will query wrong tables and so on)
stackexchange-wordpress
{ "answer_score": 2, "question_score": 1, "tags": "functions, multisite, oop, switch to blog" }
Show Recently Viewed Custom Post to the visitor without plugin I need to Show Recently Viewed Custom Posts to the visitor without plugin because my design is different. Can anyone advice me how to achieve this functionality. I'll do it. Thanks
you can achieve that by using cookies. just create a cookie on init function on single page and create a array inside cookie with time of the visit on the post. And then you can retrieve the posts according to your design.
stackexchange-wordpress
{ "answer_score": 0, "question_score": 0, "tags": "custom post types" }
Trying to update the meta description of the home page We use the Yoast SEO extension and under Search Appearance, in the meta description box, I have updated our Wordpress blog's meta description an saved the changes. ![see screenshot]( It has however been more than a month now and the description has not changed when I Google for our name. Any suggestions?
Have you checked your site's meta description tag? May be, there are more than one meta description tag. That's why, you are not seeing your preferred description in Google. If it is not the case, then Google might have ignored your preferred meta description. To solve this issue, you have to use a different one.
stackexchange-wordpress
{ "answer_score": 0, "question_score": 0, "tags": "description" }
Add active class to top-level menu items when viewing single for that post type For a menu which has only top-level links to custom post type archive pages, how can I add the `.active` class to the top-level item when viewing that post type's single? There's lots of similar questions on WPSE (like this or this), but none seem to address my specific question and make use of `.current-menu-item` or `.current-menu-ancestor` (and associated) classes, which don't appear on my menu (as I assume because the single posts aren't part of the menu list structure). The only way I can think to do this is check the current post type against the slug, but it feels a bit hacky (and doesn't allow for url rewrites, etc).
Solved using an adapted version of one of the answers from @mrbenhenson's link. function custom_active_item_classes($classes = array(), $menu_item = false){ global $post; if ($menu_item->type == "post_type_archive" ) { $classes[] = ($menu_item->url == get_post_type_archive_link($post->post_type)) ? 'current-menu-item active' : ''; } return $classes; } add_filter( 'nav_menu_css_class', 'custom_active_item_classes', 10, 2 );
stackexchange-wordpress
{ "answer_score": 0, "question_score": 1, "tags": "menus, filters" }
wp_get_attachment_image_attributes not working I move all images to a subdomain.after that there is a problem to show some pictures which have `srcset`. for the home page, I resolve the problem with the below code function alter_image_src($attr) { $attr['srcset'] = str_replace(' ' $attr['srcset']); return $attr; } add_filter('wp_get_attachment_image_attributes', 'alter_image_src'); but it does now work for images which are on post pages. Images show this way <p> <img class=" size-medium wp-image-467 alignleft" src=" alt="Zoom.From.Sky_small" width="300" height="160" srcset=" 310w, 100w" sizes="(max-width: 300px) 100vw, 300px"> </p> How can I change all `srcset` addresses like the above code. but this time for post pages.
I've replaced your `string_replace` call with `preg_replace` and converted your search string to proper regex (I use regex101 for that). Because you're trying to replace images in the content, which wordpress saves as a string, you need to find anywhere in the content with an image and replace the `src` and `srcset` for it. This should work (although if you have any script tags with a `src` attribute in it then it would attempt to replace those as well. You could probably modify that regex to only match `src` and `srcset` within an image tag but that's a bit more advanced than my regex skills will take us. function alter_image_src_in_content($content) { $content = preg_replace('~(?:(?:srcset=")|(?:src=")|(?:, ))(https:\/\/www\.example\.com\/wp-content\/uploads\/)~', ' $content); return $content; } add_filter('the_content', 'alter_image_src_in_content');
stackexchange-wordpress
{ "answer_score": 0, "question_score": 0, "tags": "images" }
Show special field when correct shipping is chosen I tried this approach: add_action( 'woocommerce_review_order_before_payment', array( $this, 'my_custom_checkout_field') ); add_action('updated_checkout',array( $this, 'my_custom_checkout_field')); public function my_custom_checkout_field(){ $chosen_methods = WC()->session->get( 'chosen_shipping_methods' ); $chosen_shipping = $chosen_methods[0]; if($chosen_shipping == 'zasilkovna'){ include_once('special-field.php'); } } However, the special field does not appear when user clicks the shipping method. User needs to manually refresh the page, which is not good. I need to hook myself on the ajax and show the field when correct shipping is clicked. I know the jqery is firing the action, but am not quite sure how to hook on it...
You need to setup the change event on the field: $('select.shipping-field').on('change', function()) { $.post( ajaxurl, { action: 'shipping_special', data: 'your data here..' }, function(response){ // The response should contain your special field HTML } ); }); You can pass the current shipping select option Then your theme's `functions.php` file needs to have the action to return your special field, if the shipping is `zasilkovna` add_action('wp_ajax_shipping_special', 'shipping_special_field' ); add_action('wp_ajax_nopriv_shipping_special', 'shipping_special_field' ); function shipping_special_field() { // Return your special field HTML here } See wp_ajax__requestaction, this tutorial from WPMUDev or this SO answer;
stackexchange-wordpress
{ "answer_score": 1, "question_score": 1, "tags": "plugin development, woocommerce offtopic, ajax" }
Remove Bulk Action For non admin user I want to remove bulk action for non admin user (shop manager to be specific), so I got this code that let me to remove the bulk action for all users. add_filter( 'bulk_actions-edit-shop_order', '__return_empty_array', 100 ); How can I make it working only for the shop manager role users? I also tried this, but it didn't work. Thanks.
Here's how you can remove bulk actions for any user not an administrator. add_action( 'wp_loaded', 'my_remove_bulk_actions' ); function my_remove_bulk_actions() { if ( ! is_admin() ) return; if ( ! current_user_can( 'administrator' ) ) { add_filter( 'bulk_actions-edit-shop_order', '__return_empty_array', 100 ); } } If you would like to target just the shop manager you can edit the if statement `if ( ! current_user_can( 'administrator' ) )` to `if ( current_user_can( 'shop_manager' ) )` Tested and working on latest version of WordPress, 5.0.3 at time of posting.
stackexchange-wordpress
{ "answer_score": 1, "question_score": 0, "tags": "woocommerce offtopic" }
WP Multisite: Are custom taxonomies specific to each site only? I'm still trying to work out what Multisite does and doesn't do... Are custom taxonomies specific to each site only or if I create a custom taxonomy on one site will others see it on another site?
Custom Taxonomies will be specific to each site. If you were to create your custom taxonomies as a plugin, you could activate this plugin in all sites and all of them will have the custom taxonomies. BUT, even then, the data that you enter into each of the taxonomies will be unique to each site. There might be a way to share them across your multisite network since all of your sites could share the same database. For this I'd recommend reading this article which explains a little more about how taxonomies and terms are stored in the database, and a possible way for you to do this. Personally I haven't tried this, but at the same time, I don't think it would be recommended, at least for most cases. < Hope this helps
stackexchange-wordpress
{ "answer_score": 2, "question_score": 0, "tags": "custom taxonomy, multisite" }
Cannot access wp admin of Wordpress website (security plugin issue) I was using all in one WP security and White Label plugin in one of my wordpress website. I had custom wp-admin login url. After moving host i realized i cannot login via custom url. Also, wp-admin is not working. I tried editing/deleting .htaccess, rename plugin folder and plugin but no luck. Even tried to disable plugins via php admin.
You can reinstall WordPress manually, **don't delete your wp-content folder** and unzip the file from < Check this Article < Thanks !!!
stackexchange-wordpress
{ "answer_score": 0, "question_score": 0, "tags": "security" }
Error "Sorry, you are not allowed to access this page" I renamed plugins folder, removed unused themes, checked wp_capabilities for my website, It's getting error like below after login page and redirecting to home page.![enter image description here](
First thing you need to do is take a backup of your current state. Then we start debugging. A lot of things could cause this error so we have to first determine the root cause. To do this go to your wp-admin folder and in the wp-config.php file add the following line of code: define( 'WP_DEBUG', true ); This will allow you to see the error that is on each page. Be sure to remove the code when you're done. When we know the error or the cause of the error it will be easier to solve. Some simple things you can start with is turning off all plugins, reverting to default theme, etc.
stackexchange-wordpress
{ "answer_score": 0, "question_score": 0, "tags": "admin, login, errors, permissions" }
Override plugin class which has namespace I would like to override this plugin class in child theme : **class-config.php** namespace um; if ( ! defined( 'ABSPATH' ) ) exit; if ( ! class_exists( 'um\Config' ) ) { /** * Class Config * * Class with global variables for UM * * @package um */ class Config { //some code here... } //end class } But as you can see, this class uses a namespace, so I can't just write this in my functions.php : **functions.php** class Config { //some new code here... } I tried to add _namespace um;_ in functions.php but of course it doesn't work. Does anybody have an idea ? :)
I found it ! :) I just created **another file** called class-config-new.php just next to functions.php. I wrote my class in class-config-new.php and added the namespace, and I added a require_once in functions.php to call the file.
stackexchange-wordpress
{ "answer_score": 1, "question_score": 0, "tags": "plugins, plugin development, pluggable, namespace" }
How to create callback function which returns all posts with specific data? I need to create a new route `all` which returns only the specified fields for all posts. add_action( 'rest_api_init', function () { register_rest_route( 'custom', 'all' ,array( 'methods' => 'GET', 'callback' => 'get_all' ) ); } ); I need to have for all posts, their id, title, link. I'm unable to create my `get_all` function. function get_all ( $params ){ $posts = get_posts( array( 'post_type' => 'post', 'post_status' => 'publish' ) ); // parse all posts and for each post returns only the specified fields wp_reset_postdata(); return rest_ensure_response( $data ); }
Found! This function returns the specified fields for each post. function get_all ( $params ){ $posts = get_posts( array( 'offset' => 0, 'post_status' => 'publish' ) ); if ( empty( $posts ) ) { return null; } $posts_data = array(); foreach( $posts as $post ) { $posts_data[] = (object) array( 'id' => $post->ID, 'date' => $post->post_date, 'date_gmt' => $post->post_date_gmt, 'modified' => $post->post_modified, 'title' => $post->post_title, 'content' => $post->post_content, 'category' => get_the_category_by_ID($post->post_category[0]), 'link' => get_permalink($post), ); } return $posts_data; }
stackexchange-wordpress
{ "answer_score": 0, "question_score": 0, "tags": "hooks, rest api, callbacks" }
Using category and its sub-categories products attributes as filter in products pages I have some categories and subcategories for each of them. And finally, some products under these subcategories. What I want is to choose some attributes of these categories and subcategories products to show in products page as a search filter. For example, I have these: Categories: computers: laptops weight color pc motherboard casing-box So, for example, I want the `color`, `weight`, and `motherboard` as filters. In this case, if a user selects `Computers` category, he can see the motherboard, color, and weight as filters available in the sidebar, but if he selects `laptops`, he can only see the `weight` and the `color` as filter in the sidebar. How can I do this in WordPress? Is it possible to do this in `Advanced AJAX Product Filters plugin`? If not is there any way to do this with any plugin or any code snippets?
It's possible to do it with Advanced AJAX Product Filters plugin. It allows you to use attributes in the filter. Follow these steps: 1. Install and activate the plugin. 2. In the right sidebar, click on **Widgets**. 3. Under **Filter By** option, select **Attribute**. Under **Atrribute** option, which is located beside **Filter By** , choose the attribute of your desired category / subcategory. 4. Finally, click on the **Save** button.
stackexchange-wordpress
{ "answer_score": 0, "question_score": 0, "tags": "woocommerce offtopic, ajax" }
Print post title with markup I have a piece of code that outputs my post title but how can I output it as an H4? Here is the code I have: `<?php echo get_the_title( $post_id ); ?>` Thanks
Using your example, you could... <h4><?php echo get_the_title( $post_id ); ?></h4> Or $h4 = get_the_title(); echo '<h4>' . $h4 . '</h4>'; More on get_the_title(). Or you could use the_title(). the_title( '<h4>', '</h4>' );
stackexchange-wordpress
{ "answer_score": 0, "question_score": 0, "tags": "title" }
Detect if you're in the “Frontend Editor” mode in Visual Composer Wordpress Marketo forms tend to break the Wordpress Frontend Editor. Now - my thoughts are to detect if I am just displaying the current page or I am in the frontend editor mode. If in frontend editor mode just to replace the normal form output with a placeholder (or just not display the JavaScript that breaks everything). If somebody has any better suggestion - do not hestitate to!
So, I've dig in the core of WPBakery Visual Composer and came up with this solution: function is_vc_build() { return function_exists( 'vc_is_inline' ) && vc_is_inline() ? true : false; } Hope it will help somebody in future as I spent lots of time on this.
stackexchange-wordpress
{ "answer_score": 2, "question_score": -2, "tags": "plugins, theme development" }
Archive: Lists itself So I have created an archive.php, set everything up, and my archive page works fine. Now I was wondering, of how I should prevent the archive page from listing itself. When accessing the page called archive for instance < without any date/category parameters set, the query of the archive page is itself, like on a normal page. So the WP Loop will of course check has_posts etc. and the list itself, but I want to add something like the latest posts if there are no "filters" applied. Anyone got an idea?
As @Milo told me in the comments, the problem lies in the fact, that the archive template shouldn't be applied to a page, but left untouched. That way WordPress will still know which template to use for displaying an archive but you can't access the template itself, which means it will not display itself in the query.
stackexchange-wordpress
{ "answer_score": 0, "question_score": 0, "tags": "loop, pages, archives" }
Change Category Widget Dropdown List Select Name How can change the text for "Select a category" in the product category widget? ![enter image description here](
function _category_dropdown_filter( $cat_args ) { $cat_args['show_option_none'] = __('My Category'); return $cat_args; } add_filter( 'widget_categories_dropdown_args', '_category_dropdown_filter' );
stackexchange-wordpress
{ "answer_score": 0, "question_score": 1, "tags": "woocommerce offtopic" }
Category Page Template not Showing Posts I am trying to get this template to work.
You should never create your own custom `WP_Query` queries on category templates (or any other archive template) and use them as main loop. Why? Because it will break pagination. WordPress will still create all pagination links for such archives based on default query. So if you want to modify the query in such way, that is should get all posts ordered by date, then you should use `pre_get_posts` action (add this to `functions.php` file): function show_all_posts_on_category_archives( $query ) { if ( ! is_admin() && is_category() && $query->is_main_query() ) { $query->set( 'posts_per_page', -1 ); $query->set( 'orderby', 'date' ); // you shouldn't need this one - date is default value } } add_action( 'pre_get_posts', 'show_all_posts_on_category_archives' ); And after using that code you can use typical loop in your template file: while ( have_posts() ) : the_post(); ... endwhile;
stackexchange-wordpress
{ "answer_score": 0, "question_score": 1, "tags": "posts, categories" }
Is it possible to install WordPress Multisite on a subdomain with subdirectories? This is something I have never tried so far. On a webspace I want to have a subdirectory like this: > blognetwork.example.com Then I want to run Multisite with subdirectories like this: blognetwork.example.com/blog/ blognetwork.example.com/site1/ blognetwork.example.com/site2/ Is this possible or will it lead to unpredictable issues? Someone ever tried this?
Yes, it is. All you need to do is to install your WordPress on the subdomain, turn the Multisite on and set it to use subdirectories for sites. Make sure the following is set in multisite constants: define( 'SUBDOMAIN_INSTALL', false );
stackexchange-wordpress
{ "answer_score": 2, "question_score": 0, "tags": "permalinks, multisite, installation, subdomains" }
How to set subcategory in Woocommerce? Hello I wanna to ask how can we set a sub category of a post in wordpress programatically? wp_set_object_terms( $post_id, 'Lense', 'product_cat', false); wp_set_object_terms( $post_id, 'Canon', 'product_cat', true); But what it does is not setting the parent and child category it set as both parent category
You will have to first insert the term as required using wp_insert_term. wp_set_object_terms( $post_id, 'Lense', 'product_cat', false); This function checks if 'Lense' term exist in product_cat or not. If does not exist, then create and assign. Check whether term already exists or not $id = term_exists( 'canon','product_cat',$parent_id ) //$parent_id is parent term id, in your case id of Lense if($id == NULL) { $id = wp_insert_term( 'Canon', // the term 'product_cat', // the taxonomy array( 'description'=> 'Test description', 'slug' => 'canon', 'parent'=> $parent_term['term_id'] // get numeric term id of parent - Lense ) ); } wp_set_object_terms( $post_id,$id, 'product_cat',true); This will work. // No space is allowed in taxonomy name
stackexchange-wordpress
{ "answer_score": 0, "question_score": 0, "tags": "woocommerce offtopic" }
Passing a variable to hyperlink text? Hope the question is not phrased badly Is it possible to pass a variable to for example having an: echo '<a href="' . esc_url( $link ) . '"> $link </a>'; so that the hyperlink is the same as the printed out version always?
Sure, you only need to concatenate it again. Try: echo '<a href="' . esc_url( $link ) . '">' . $link . '</a>';
stackexchange-wordpress
{ "answer_score": 0, "question_score": 0, "tags": "url rewriting, urls" }
Wordpress the_category(); only works with message-posts not with project posts, how do I specify project categories? The title, the permalinks & even the field of ACF do work smoothly. But the code is not reactive to project categories, when I echo wp_list_categories(); it shows the list of message posts only. How do I specify that it should echo project categories instead? Current code: $args = array( 'post_type' => 'project', 'posts_per_page' => 10); $loop = new WP_Query( $args ); while ( $loop->have_posts() ) : $loop->the_post(); echo '<ul>'; echo '<li>';the_title(); echo '</li>'; echo '<li>';wp_list_categories(); echo '</li>'; echo '<li>';the_category(); echo '</li>'; echo '<li>';the_field(Prijs); echo '</li>'; echo '</ul>'; endwhile;
`the_category` and `wp_list_categories` are for the `category` taxonomy term. What most people call a category is most likely a taxonomy. Category is just a default taxonomy for the `post` post type. You need to use the general taxonomy functions such as the_terms and get_the_term_list. echo '<li>'; echo get_the_term_list($post->ID, 'project_category'); echo '</li>'; You will need to change `project_category` to whatever custom taxonomy name you have used.
stackexchange-wordpress
{ "answer_score": 0, "question_score": 0, "tags": "posts, categories" }
Bootstrap version conflict 3 with 4 for wordpress theme and plugin I've developed One new wordpress plugin, using Latest Bootstrap (4) and latest FontAwesome (5) version. Is now looking good. All design is complete. Now When I install this plug-in with another website. Which website theme using old bootstrap (3) version and old fontawesome version. Then my design or existing theme design will be broken, It's version conflict 3 and 4. So How can I resolve this issue? How can I load this bootstrap 4 only for my plugin? Or how can I avoid 3 or 4 version conflict? Please suggest me.
Although this is possible, you really don't want to load multiple versions of libraries as it's going to make your site slow to load. You could try and use Bootstrap with a pre-processor like SASS with mixins to target just your plugin code and not the rest of the theme. FontAwesome 4 and 5 seem to use different prefixes `fa-` and `fas-` so you could load FA5 before FA4 as per this post. Lastly, you could
stackexchange-wordpress
{ "answer_score": 0, "question_score": 1, "tags": "plugin development" }
Check if post is added manually or through wp_insert_post() I might not be thinking this right but here is my situation: * I have a custom post type called `events`. * Some of my events are imported from an API and inserted through `wp_insert_post()` (in a plugin), some are added manually in the admin edit screen. * On post saving I need to add some informations to the `post_meta` but **only if the post is added manually (through the admin edit screen)**. So I am hooking into `save_post_events` and performing some security checks but I have no idea how to check if the request is only coming from the admin edit page because right now the `save_post` action triggers also if the post is added with the `wp_insert_post` function. Any ideas? Thanks
I have found a solution without adding any other metaboxes. I haven't thought about it but the import function in my plugin uses a `nonce` so I just check if my nonce is set or not. Here is my `save_post_events` function: add_action( 'save_post_events', 'wse_327066_example', 10, 3); function wse_327066_example( $post_id, $post, $update ) { if ( defined( 'DOING_AUTOSAVE' ) && DOING_AUTOSAVE || $post->post_status == 'trash' || !current_user_can( 'edit_posts' ) || isset( $_POST['_import_nonce'] ) ) return; # Now I can do whatever I want with posts saved from the admin edit screen... }
stackexchange-wordpress
{ "answer_score": 0, "question_score": 1, "tags": "wp insert post, save post" }
Cant play videos I have a movies folder called movies located in site root/wp-content/movies/. I also have a template creates in my theme called page-movies.php. And a wordpress page called movies using the page-movies.php template. What is the correct way to display the list of movie urls in the movies folder on the movies page. I've used a scandir() inside of A tags to display all the urls as "site.com/movies/movietitle.mp4" but I click thr link to the movie is loads nothing just a blank white page. Is there a correct way I should be loading the list of movie urls onto a oage from a directory?
If you movies are stored in `/wp-content/movies/` and the URLs are `site.com/movies/movietitle.mp4` then the links are pointing to the wrong place. Change the URL's to include the `wp-content` path eg `site.com/wp-content/movies/movietitle.mp4` Separate to your question, you could look at having your `page-movies.php` template load the links into a video element using javascript.
stackexchange-wordpress
{ "answer_score": 0, "question_score": 0, "tags": "videos" }
2nd level (drop-down) of the navigation menu not working Second level of my navigation menu (drop-down) doesn't seem to be working. Things to note: * It's not loading into the site (i.e. not showing in source code _image below_ ) * I'm using bootstrap 4 for the layout of my theme (the menu is not bootstrap however) * I'm trying to get prouct categories in dropdown, though other pages aren't showing either I have spent 3 hours looking for a solution. Any idea to what the issue is would be greatly appriciated! !enter image description here ![enter image description here](
The issue was that I had `'depth' => 1,` instead of `'depth' => 3`. I didn't allow my nav to have more than 1 in depth essentially.
stackexchange-wordpress
{ "answer_score": 0, "question_score": 0, "tags": "menus" }
Can I hide certain upload folders in media library A Plugin ( download monitor ) saves uploaded files in a certain folder called "dlm_uploads" within the WP upload directory. All files are visible in Media Library. Unfortunately the upload path cannot be changed in the plugin. can I hide this folder in the media library? thanks
Perhaps a bit quick and dirty, but this should work: function media_library_hide_dlm_downloads($where) { if(isset($_POST['action']) && ( $_POST['action'] == 'query-attachments')) { $where .= ' AND guid NOT LIKE "%wp-content/uploads/dlm_downloads%"'; } return $where; } add_filter('posts_where', 'media_library_hide_dlm_downloads'); Read more about the posts_where filter.
stackexchange-wordpress
{ "answer_score": 1, "question_score": 2, "tags": "functions, uploads, media" }
Workaround for: PHP syntax error, unexpected T_STRING in load.php on line 1104 (when installing) I’ve received the error: > PHP Parse error: syntax error, unexpected T_STRING in /web/www/html/xxx/wordpress/wp-includes/load.php on line 1104 trying to install wordpress on a linux server. Googling the problem I’ve found that the error depends on a older version of PHP and it is solved in PHP version 5.6 (at least). See for instance this support issue. My question is: there is a workaround to solve this problem without updating PHP? (I do not control the server) Current version of PHP is 4.4.8. Many thanks in advance.
WordPress doesn't run on PHP 4. This version is **10 years** old and completely broken by any current standards. You have to use a newer PHP version, there is no workaround. You can always look up the current requirements on wordpress.org. Right now, PHP 7.3 is recommended, but 5.6 might still work. If you can't change the PHP version, find a better host.
stackexchange-wordpress
{ "answer_score": 5, "question_score": 0, "tags": "php, installation" }
Get array of posts from the current archive page loop Classic WordPress loop (for example in `archive.php`) looks like this: if ( have_posts() ) : while ( have_posts() ) : the_post(); get_template_part( 'template-parts/content', get_post_format() ); endwhile; endif; I want to get an array of post objects on archive page without having to do this: $my_posts = array(); while ( have_posts() ) { the_post(); $my_posts[] = $post; } // $my_posts is array of post objects Is there any simpler method to get it?
That’s pretty easy. All you need is this: global $wp_query; $my_posts = $wp_query->posts;
stackexchange-wordpress
{ "answer_score": 7, "question_score": 4, "tags": "wp query, loop" }
Query post with meta_query where date is not in future In my args I would like to **exclude** posts where the datum_event is **not in the future**. Currently it only displays posts with datum_event values that are in the past, but because older posts don't have any value for datum_event, the old posts don't get shown. I know how to compare against a single value, but how do I compare against all future dates? Basically: EXCLUDE posts with `datum_event` `compare` future. $args = array( 'post_type' => 'agenda', 'paged' => $paged, 'meta_query' => array( array( 'key' => 'datum_event', 'value' => date('Ymd'), 'compare' => '<=' ) ), );
You might try adding a second meta_query that would look for anything without the meta key: $args = array( 'post_type' => 'agenda', 'paged' => $paged, 'meta_query' => array( 'relation' => 'OR', array( 'key' => 'datum_event', 'value' => date('Ymd'), 'compare' => '<=' ), array( 'key' => 'datum_event', 'meta_compare' => 'NOT_EXISTS', 'value' => 'placeholder' ), ), ); Note that the value of placeholder is required to the make the not exists work - see < This is untested code but hopefully it helps!
stackexchange-wordpress
{ "answer_score": 4, "question_score": 1, "tags": "wp query, post meta, query posts, sql" }
How to differentiate between email subscription list and blog subscription list? I would like to segregate the emails I collect on my wordpress site, is it possible? I’d like to separate the emails such that the main subscription emails go to my newsletter list. And visitors have to visit the blog in my website and subscribe to specifically subscribe to blog feed. So I’ll end up generating 3 email lists from one site: 1. People who subscribe to newsletters only 2. People who subscribe to blog feed only 3. People who subscribe to both In case this piece of info is of use, I’m using Divi from elegant themes to build my site. IT noob here so any help would be greatly appreciated. Thank you!
You can try using Email Subscribers & Newsletters plugin. You can use it to manage all blog post notification emails and newsletters in one single place.
stackexchange-wordpress
{ "answer_score": 1, "question_score": 0, "tags": "email, subscription" }
Is <title> tag default in WordPress? This may be a stupid questions but I have been building some themes. Some of them doesn't include the `<title>` in the head and some of the theme include it. I belive some SEO plugin can add `<meta>` tag in the head but what about title? So, is it because the SEO plugin or it is default by WordPress included in `wp_head()`?
Well, it's not a stupid question at all... `wp_title` is a template tag and it was used for a long time (since 1.0.0) to put `<title>` tag in the header. This way plugins were able to modify the title with filters. In WP 4.4 it was about to be deprecated, but that idea was abandoned and you can still use that function. On the other hand, you don't have to. Since WP 4.1 you can use `title-tag` theme feature instead. So if your theme declares that it supports `title-tag` feature, then the title tag will be generated automatically and you don't have to put it manually in the header any more. And to declare that you're supporting such feature you need something like this in your code: function theme_slug_setup() { add_theme_support( 'title-tag' ); } add_action( 'after_setup_theme', 'theme_slug_setup' );
stackexchange-wordpress
{ "answer_score": 3, "question_score": 2, "tags": "theme development, seo" }
Store post in raw markdown format, no html? Is it possible to store posts in pure markdown format? so that I can retrieve the content through the REST API and get the markdown code, without any added html?
You can try `remove_filter( 'the_content', 'wpautop' );` to remove the added HTML tags. <
stackexchange-wordpress
{ "answer_score": 1, "question_score": 0, "tags": "plugins, rest api, markdown" }
WPDB: how to get the value of a field in a custom database table For my WordPress site, I would like to echo the value of a column in a row (determined by the user's ID) of a table in the database for my site. This table was created by a plugin so it is not accessible through the user meta. I have to try and get the value from the table created by the plugin. For this example, the value is located in the "plugintable" table in the database and the column is "columnname". How get I get the value based on matching the user's ID with the "ID" row? I've gotten here from the help of other online sources, but I'm stuck. <?php global $wpdb, $table_prefix; $user_ID = get_current_user_id(); $value = $wpdb->get_var('SELECT columnname FROM '.$table_prefix.'plugintable WHERE ID = '.$user_ID); echo $value; ?>
OK, so first of all, you should always use proper escaping, when building the queries. This is how your code can look after fixing: global $wpdb; $value = $wpdb->get_var( $wpdb->prepare( " SELECT column_name FROM {$wpdb->prefix}plugin_table WHERE ID = %d ", get_current_user_id() ) ); The things you have to take care of: 1. You have to change `column_name` to proper column name you want to get. 2. You have to change `plugin_table` to proper table name you want to get the value from. 3. You have to change `ID` to proper name of column that stores the user id in given table.
stackexchange-wordpress
{ "answer_score": 5, "question_score": 2, "tags": "php, database, wpdb, sql" }
Random order of WP_Query results with highest meta value I need to random of cars with highest price. My code: $argsLoop = array( 'post_type' => 'cars', 'posts_per_page' => 12, 'paged' => 1, 'meta_key' => 'cars_price', 'orderby' => 'cars_price', 'order' => 'DESC' ); How to leave the result of this query random?
OK, so you're almost there. Let's say you have this query: $argsLoop = array( 'post_type' => 'cars', 'posts_per_page' => 12, 'paged' => 1, 'meta_key' => 'cars_price', 'orderby' => 'cars_price', 'order' => 'DESC' ); $cars = new WP_Query( $argsLoop ); // All you have to add is this line: shuffle( $cars->posts ); Now you can do standard loop and the selected cars will be showed in random order.
stackexchange-wordpress
{ "answer_score": 1, "question_score": 1, "tags": "php, wp query, post meta" }
ACF not showing I have a (weird) issue - can't get the ACF field to work on my page. I have a simple `text_field` and it shows on the `Homepage` page section: ACF settings: ![enter image description here]( * * * Homepage settings (when I refresh the panel it shows `Lorem ipsum` so it's saved in the databse): ![enter image description here]( And in my `index.php` page I have: <?php $hero = the_field('hero_title'); /* tried also */ /* $hero = get_field('text_field'); */ echo '<h1>'.$hero.'</h1>'; ?> Where it shows the blank `<h1></h1>` on my page: ![enter image description here]( What am I doing wrong? I also tried with `group` type and I have the same issue.
`the_field()` function shows the value and it doesn't get/return anything. Like `the_title()` and other template tags starting with `the_`. It means that: This line prints the value and `$hero` variable is empty. $hero = the_field('hero_title'); This line prints only `<h1>` tags. echo '<h1>'.$hero.'</h1>'; What you want is: echo '<h1>' . get_field('hero_title') . '</h1>';
stackexchange-wordpress
{ "answer_score": 2, "question_score": 0, "tags": "functions, theme development, custom field, advanced custom fields" }
Showing my server ip in source code for several links not for all links So my problem is that I have hosted my wp from my localhost to aws light sail and assigned a static IP to my instance and then I mapped the website with my subdomain and then changed site address and wp address from wp-config to my subdomain then almost all the pages, posts and media showing my domain in source but two custom pages and some media items still showing IP address and because of that I am getting SSL warning because IP address does not have any SSL but my domain has. Any workaround will be appreciated.
If you have previously added an image to a post or page inside the content, then that is saved as HTML with the URL as it was at the time of being added. So if you want to retroactively change media URLs inside content you need to do a search replace in the database.
stackexchange-wordpress
{ "answer_score": 1, "question_score": 0, "tags": "urls, subdomains, site url, hosting, home url" }
Access WP_REST_Server from within plugin namespace I am new to OOP and developing plugins. I have developed a plugin using the Plugin-Boilerplate with namespace. I expanded the boilerplate to include a REST folder and class so I could create custom routs/endpoints. It is working; however I cannot use the WP_REST_Server object. I get the following error: ..class-wp-rest-server.php does not exist.From my limited knowledge of oop my guess I it is not in my namespace. But how do I include/access it? My guess is there is a simple mechanism that is obvious to experienced OOPs. Thanks.
WordPress (version 5.0) doesn't use namespaces for it's classes, so try to use the global one: \WP_REST_Server to avoid assuming it's in your custom namespace. One of the reason for this is that WordPress supports PHP 5.2.4+ that doesn't support namespaces. The minimum is PHP 5.3.3+, if I remember correctly, to support it. Later this year (2019) WordPress plans to bump the minimum required PHP version to 5.6 and then to 7 at the end of the year. So after that, WordPress namespaces could be possible, but I'm not aware of any such planned changes though :-)
stackexchange-wordpress
{ "answer_score": 4, "question_score": 0, "tags": "plugins, rest api, namespace" }
Is a very simple theme secure enough? I am very very new to Wordpress theme development and after creating one, I want to know if any threats will face it. There is no way i receive any data from visitors, including no comments received. There are no forms nor any plugins to receive any data. What I want to know is if the theme I've created is secure enough to be used as a news website or not. Thank you very much in advance.
If you follow the guidelines of the Codex for Themes (start here: < ), and ensure that any user-supplied input (if any) is sanitized, then a theme will be secure. This also assumes that you have done basic security on your install. For instance: * strong passwords on all accounts * create an admin account without the 'admin' name * take the first user account and demote it to subscriber (not an admin) * strong passwords for your hosting account * strong passwords for any FTP users on your hosting account * keeping all plugins current/updated * updating WordPress to current levels * use latest PHP version on your site Then your site will be less susceptible to attack. You'll also find lots of security guidelines via the googles. Look at them carefully and apply those that are needed.
stackexchange-wordpress
{ "answer_score": 1, "question_score": 0, "tags": "themes, security" }
Qtranslate-X get raw post title value How can I get a raw value of post title using Qtranslate-X plugin? I have 2 active languages - [:et] and [:ru] $posts = get_posts($args); if($posts){ foreach($posts as $post){ $title1 = $post->post_title; $title2 = get_post_field( 'post_title', $post->ID, 'raw' ); echo $title1; echo $title2; } } Variables $title1 and $title2 returns only [:et] versions of a title. Database value of post_title is: [:et]Immuniseerimise jätkukursus[:ru]Иммунизация – дополнительный курс[:]
**post_title_ml** property should be used to get a raw post value, instead of **post_title** $title = $post->post_title_ml To translate raw value **translate_text** filter can be used $english_title = apply_filters('translate_text', $title, 'en'); Or **qtranxf_use_language()** function $english_title = qtranxf_use_language('en', $title, false, true);
stackexchange-wordpress
{ "answer_score": 0, "question_score": 0, "tags": "translation, multi language, language" }
Set default image link target in Gutenberg image block I want to set the _default_ target of the image block in Gutenberg to "Media File": ![Link target]( I've found solutions for the classic editor, and one that appears to work for Gutenberg galleries by editing the block's template, but I was under the impression that the intended way to modify the editor's behaviour is via JavaScript hooks in the block editor. Is there a way to set the default target using a JavaScript hook in the block editor? UPDATE: I made a pull request on the Gutenberg GitHub repository to try to implement the ability to override the default link target with a plugin. The latest version is here. As of writing, this has not yet been merged.
This was (finally) fixed to Gutenberg (and will be applicable for both the image and the gallery blocks); and will add an option to WordPress options' database table. this was done in < and < It'll be added to WordPress 5.6 but it's already available in the Gutenberg plugin. To link the image to the file by default, issue the following in your theme or plugin: add_action( 'after_setup_theme', function() { update_option( 'image_default_link_type', 'file' ); }); Replace `file` with `attachment` if you want to link to the attachment page for some reason, or `none` if you don't want to the image to have a link. As for javascript: modifying blocks so that they alter the site's options is possible in Gutenberg although I haven't gotten it to work yet, check out: < Note that if you try do the image_default_link_type equivalent in javascript, don't use "file" and "post" as the options (as long as this ticket is open) - see <
stackexchange-wordpress
{ "answer_score": 3, "question_score": 11, "tags": "images, javascript, hooks, media, block editor" }
IF taxonomy archive is hierarchical THEN I'm trying to put in a conditional in my `archive.php` that sorts our whether the taxonomy is hierarchical or not. This is what I have so far but it doesn't work. <?php if ( is_taxonomy_hierarchical() ) { ?> I am a hierarchical tax <?php } else { ?> I am NOT a hierarchical tax <?php } ?>
Look at the docs ( _please_ read the docs) for `is_taxonomy_hierarchical()`. You need to tell it which taxonomy you're checking: if ( is_taxonomy_hierarchical( 'my_taxonomy_name' ) ) { } If you're template isn't specific to a taxonomy, and you need to know which taxonomy you're viewing, use `get_queried_object()` to figure it out (you were already told how to do this, by the way): if ( is_tax() ) { $taxonomy = get_queried_object()->taxonomy; if ( is_taxonomy_hierarchical( $taxonomy ) ) { } else { } }
stackexchange-wordpress
{ "answer_score": 2, "question_score": -1, "tags": "taxonomy, conditional tags, archive template" }
How to create an unordered list of images separate from the content Some of the solutions I'd tried are 'multiple featured images,' and 'upload image gallery,' but they're either require plugins, are too convoluted, or make for terrible html syntax. I've looked around at websites that use wordpress, and found this, and would like to know how they might have coded their list of images at the bottom of their 'Projects' post in the backend:
I would recommend using Wordpress _custom fields_. You can add them using the Wordpress API or using a plugin like **Advanced Custom Fields** If so, create a **Repeater field** that contains **Image field**. Use this to show your repeater field.
stackexchange-wordpress
{ "answer_score": 0, "question_score": 0, "tags": "php, images" }
need to exclude APP_TAX_STORE => $term->slug I have this code: query_posts( array( 'post_type' => APP_POST_TYPE, 'post_status' => 'publish', 'posts_per_page' => 4, ), ) ); now I need to remove all post from this Query `APP_TAX_STORE => $term->slug` Meaning I need to show all posts except the one from this one taxonomy.
Okay found a solution that's working as well: query_posts( array( 'post_type' => APP_POST_TYPE, 'post_status' => 'publish', 'posts_per_page' => 4, 'tax_query' => array( array( 'taxonomy' => APP_TAX_STORE, 'field' => 'slug', 'terms' => $term->slug, 'operator' => 'NOT IN', ), ), ) );
stackexchange-wordpress
{ "answer_score": 0, "question_score": 1, "tags": "wp query" }
Wordpress override archive page template using a plugin I am editing the archives template of my wordpress archive pages for specific post types and taxonomies only and I want to package it all in one plugin instead of adding it on my functions folder and adding all files inside my themes folder. Is there a way to do this on wordpress? I am not sure I looked in the documentation.
You should create a filter to the `archive_template` template hook. function use_custom_template($tpl){ if ( is_post_type_archive ( 'books' ) ) { $tpl = plugin_dir_path( __FILE__ ) . '/tpl/dir/books-archive.php'; } return $tpl; } add_filter( 'archive_template', 'use_custom_template' ) ;
stackexchange-wordpress
{ "answer_score": 2, "question_score": 0, "tags": "plugins, child theme, archive template" }
Echo Text If User Is Logged in But NOT the Author of post i am coding a plugin, where user can subscribe to a indvidual author of post (like we do on YouTube). I want to display the subscribe link to all logged in users, but not the author of post. my plugin gets the author id for each post and display's the link. Problem is author would not subscribe to his own self, So in short i want a way to echo a link, if current user is NOT the author of the post.
Try something like this in your template tags (or wherever in your theme): function should_display_link() { $post = get_post(); // Something went wrong, bail. (You should always have a post, in theory) if ( ! $post ) { return false; } $current_user = get_current_user_id(); // Assuming only logged-in users can subscribe. if ( ! $current_user ) { return false; } return absint( $post->post_author ) !== absint( $current_user ); } In your template, you can use it like this: <?php if ( should_display_link() ) : ?> <!-- Your link code here --> <?php endif; ?>
stackexchange-wordpress
{ "answer_score": 1, "question_score": 0, "tags": "posts, users, login, author, debug" }
Add metabox to document tab in gutenberg ![enter image description here]( How can I add custom metabox in document tab in gutenberg? There is documentation about adding plugin sidebar here, but I'm looking for adding custom metabox in existing document tab.
Here is the solution. Hope it will help you const { registerPlugin } = wp.plugins; const { PluginDocumentSettingPanel } = wp.editPost; const MyDocumentSettingTest = () => ( &ltPluginDocumentSettingPanel; className="my-document-setting-plugin" title="My Panel"> &ltp;>My Document Setting Panel</p> </PluginDocumentSettingPanel> ); registerPlugin( 'document-setting-test', { render: MyDocumentSettingTest } ); <
stackexchange-wordpress
{ "answer_score": 7, "question_score": 5, "tags": "custom field, metabox, block editor" }
meta query or with meta value within one of my `query_posts` I use `'meta_key' => 'clpr_topcoupon', ;meta_value'=> 1,` now I would like to show post without as well but the one with `meta_value` first. I tried: 'meta_query' => array( 'relation' => 'OR', array( //check to see if date has been filled out 'meta_key' => 'clpr_topcoupon', 'meta_value'=> 1, ), array( //if no date has been added show these posts too 'meta_key' => 'clpr_topcoupon', 'meta_value'=> 0, ) ), However it is not working. It shows the one with `0` first.
'meta_key' => 'clpr_topcoupon', 'orderby' => 'meta_value_num', 'order' => 'DESC' You can solve the problem by using order by clause then there will no need to write meta query. Please use the above code to solve your problem.It will show the posts according to descending order of the value in meta key.
stackexchange-wordpress
{ "answer_score": 1, "question_score": 0, "tags": "meta query, array" }
Solved: redirect to another page using functions.php I want users to change their avatar on a general site, because some plugins only work with that. for example > www.example.com/members/user1/profile/change-avatar/ And > www.example.com/members/user2/profile/change-avatar/ Should both redirect to > www.example.com/change-avatar/
Solved it. add_action('init','redirect_to_change_avatar'); function redirect_to_change_avatar() { if ( strpos($_SERVER['REQUEST_URI'], '/profile/change-avatar/') !== false ) { wp_redirect('/change-avatar/'); exit; } }
stackexchange-wordpress
{ "answer_score": 1, "question_score": 0, "tags": "functions, redirect" }
How can I compel alphanumeric entries for username textbox on woocommerce registration form I am having a bit of a challenge with Woocommerce registration form. Currently, users are able to register using all numeric characters as their usernames. I can't think of a way to enforce that they use only alphanumeric combinations. Not only numbers. I can't seem to find any answers anywhere.
You can use the `woocommerce_registration_errors` hook to validate the username & set an error if your conditions aren't met - WooCommerce will bail and pass the error back to the UI for the user: add_filter( 'woocommerce_registration_errors', function ( WP_Error $errors, $username ) { if ( ! preg_match( '/[a-z]/i', $username ) ) { $errors->add( 'username', 'Username must contain alphabetic characters.' ); } return $errors; }, 10, 2 );
stackexchange-wordpress
{ "answer_score": 1, "question_score": 0, "tags": "woocommerce offtopic" }
Change the category of all posts in it I'm trying to make a category change of some posts by MySQL. But I am not able to give the update in the database, it is giving error when running the query. UPDATE * FROM mooca_posts LEFT JOIN mooca_term_relationships ON (mooca_posts.ID = mooca_term_relationships.object_id) LEFT JOIN mooca_term_taxonomy ON (mooca_term_relationships.term_taxonomy_id = mooca_term_taxonomy.term_taxonomy_id) SET mooca_term_taxonomy.term_id = '112' WHERE mooca_term_taxonomy.term_id IN (1448) GROUP BY mooca_posts.ID I need to change from category 1448 to 112.
UPDATE wp_term_relationships SET term_taxonomy_id = 112 WHERE term_taxonomy_id = 1448 Try this
stackexchange-wordpress
{ "answer_score": 1, "question_score": 1, "tags": "categories, mysql" }
Menu flickering with each refresh on Google Chrome I am completely at a loss with how to fix this issue and am hoping someone more knowledgeable than me can provide some insight. At random, my website jaci.moe has started to have some issues with the menu flickering on each refresh. The issue does not seem to occur (or at least it does to a less noticeable degree) in both Safari and Firefox. I have tried turning off plugins to isolate it and removed my custom CCS to see if that was the culprit. Neither turned up with any solutions. Would be so grateful for any insight someone can provide! Thank you.
Looks to be a case of flash of un-styled text as you are using "Archivo Medium" from Google Web Fonts for your menu. There is a CSS property font-display which would help in your case, however the Google Webfonts don't use this currently. There's an issue which raises this on GitHub. There are a few workarounds, which would be better explored on StackOverflow (as this isn't a Wordpress issue), but you could take a look at this article from TutsPlus. It makes use of the TypeKit webfontloader.
stackexchange-wordpress
{ "answer_score": 0, "question_score": 0, "tags": "menus" }
Function to check if author has posted within the last x days Is is possible to check whether an author has posted in the last X days? I am currently using this function to determine whether he has posted at all. $args = array( 'post_type' => 'your_custom_post_type', 'author' => get_current_user_id(), ); $wp_posts = get_posts($args); if (count($wp_posts)) { echo "Yes, the current user has 'your_custom_post_type' posts published!"; } else { echo "No, the current user does not have 'your_custom_post_type' posts published."; }
Yes, it is possible and it is pretty small change in your code... `get_posts()` uses `WP_Query`, so you can use all params from this list: < So here's your code after changes: $args = array( 'post_type' => 'your_custom_post_type', 'author' => get_current_user_id(), 'date_query' => array( array( 'after' => '- X days', // <- change X to number of days 'inclusive' => true, ), ), 'fields' => 'ids', // you only want the count of posts, so it will be much nicer to get only IDs and not all contents from DB ); $wp_posts = get_posts($args); if (count($wp_posts)) { echo "Yes, the current user has 'your_custom_post_type' posts published!"; } else { echo "No, the current user does not have 'your_custom_post_type' posts published."; }
stackexchange-wordpress
{ "answer_score": 1, "question_score": 1, "tags": "wp query, functions, author, get posts" }
Check if `do_action()` in WordPress returns any result I want to check if `do_action('some_hook')` in WordPress returns/echoes any result for a specific post. I've tried using `has_action('some_hook')` but it only checks if `'some_hook'` has any registered handler at global level, it does not check if a specific post has any result for that hook. Can anybody please tell me how to achieve what I want?
One possible way could be to use PHP's output buffering via `ob_start()` like so ob_start(); do_action('my_hook'); $content = ob_get_contents(); ob_end_clean(); if (empty($content)) { // no output generated } else { // had some output }
stackexchange-wordpress
{ "answer_score": 3, "question_score": 0, "tags": "hooks, actions" }
remove author and date from all posts I've tried including some code in style.css of my theme, but it didn't work. Ex: body.blog .posted-on, body.blog .post-author, body.blog .post-comments, body.blog .entry-taxonomy { display: none; } I'm trying to remove the author and the date from the post.
For those who have the same issue, I solved it by doing the following: Within Apparence -> Customize -> Blog Post Options -> * uncheck "post Date" * uncheck "post Author" These settings, removed the author and date from the post. Then, commenting the following line from single.php /*$cmsms_post_author_box = get_post_meta(get_the_ID(), 'cmsms_post_author_box', true);*/ And then, I've changed with the following: $cmsms_post_author_box = ""; These, removed the bottom "About the author"
stackexchange-wordpress
{ "answer_score": 0, "question_score": -1, "tags": "css, author, date" }
How to hide custom taxonomy archives same way as hiding custom post types? I'm trying to make it so my custom taxonomy terms don't have archive pages. I achieved something similar for a custom post type using "publicly_queryable' => false". I tried this from the docs inside the register_taxonomy function: 'public' => false, 'rewrite' => false, Which works.. but it also removes the ability to view the taxonomy from anywhere in the dashboard.
If you set `public` to false, this taxonomy will get hidden in all places. So if you want it to be visible in wp-admin, you’ll have to also set `show_ui` to true - it will show the admin interface to manage this taxonomy. You can see the full list of params here: < And here is a generator, that may be a nicer way to create code for registering taxonomies/posts: <
stackexchange-wordpress
{ "answer_score": 6, "question_score": 3, "tags": "custom taxonomy, archives" }
Programmatically add custom field to post_name in a custom post type I have a simple custom post type set up for Events. I'm using Carbon Fields to add a Start Date field which I would like to include in the post_name. For example: < I'd like to have the post_name created when they save the event, adding the custom field "cw_event_start_date" to the post_name to prevent the URLs from looking like this: < < < We won't have to worry about duplicate events on the same date, and if they did it should create the post_name as "20180401-staff-meeting-2".
You can filter the slug creation on `wp_unique_post_slug` hook. //Register the filter add_filter('wp_unique_post_slug','prefix_the_slug',10,6); function prefix_the_slug($slug, $post_ID, $post_status, $post_type, $post_parent, $original_slug){ //Get value from the custom field $prefix = get_post_meta($post_ID,'cw_event_start_date',true); //Only prefix certain post type and if prefix field existed if($post_type==='post' && $prefix && !empty($prefix)){ //Prefix only if it is not already prefixed preg_match ('/^\d\d\d\d\d\d/', $slug, $matches, PREG_OFFSET_CAPTURE); if(empty($matches)){ return $prefix.'-'.$slug; } } return $slug; }
stackexchange-wordpress
{ "answer_score": 1, "question_score": 0, "tags": "custom post types, url rewriting" }
Do not load the categories in Category.php I have a CPT and each post has categories and sub categories. When I enter the Category.php page this does not print any post. <?php get_header(); ?> <div class="row"> <div class="col-12 float-left mt-3"> <h1>Category <span><?php single_cat_title(); ?></span></h1> </div> </div> <div id="pro" class="row"> <div class="col-12 col-lg-3 float-left"> <?php get_sidebar(); ?> </div> <div class="col-12 col-lg-9 float-left"> <?php while(have_posts()): the_post();?> <?php the_title();?> <?php endwhile;?> </div> </div> </div> <?php get_footer(); ?>
First of all the template is `category.php` (without a capital letter. Second of all, you say you have a > Custom Post Type with categories most likely you mean you have a > Custom Post Type with a Custom Taxonomy In order to design a custom page template to show cpt from a custom taxonomy, you need to use name your template `taxonomy.php`. Please see the template hierarchy for more details.
stackexchange-wordpress
{ "answer_score": 0, "question_score": 0, "tags": "custom post types, categories" }
How to safely escape the title attribute I'm going through some training on internationalization and escaping data. But I feel stuck with escaping the title attribute. I have the following code in a helper function... echo '<h2 class="m-title">'; printf( esc_html__('%s','tn'), '<a href="'.esc_url(get_permalink()).'" title="'.the_title_attribute().'"> '. esc_html(get_the_title()).' </a> ' ); echo '</h2>'; Everything appears to be working fine with it, except the title attribute. The output looks like this.... Hello world! Hello world! Because the DOM is loading the following: <h2 class="m-title"> Hello world! <a href=" title=""> Hello world! </a> </h2> What I am doing wrong with calling `the_title_attribute()`? According to the docs, its already escaped. Thanks for any tips!
Some screen readers read the title attribute plus the link text - so those visitors would hear "Hello world! Hello world!" - so unless your real title attribute is different than the link text and provides additional context to users of screen readers, you may wish to just not use the title attribute. Or, you should be able to rewrite everything so that instead of echoing you have something like <?php // your other code here ?> <h2 class="m-title"> <a href="<?php echo esc_url(get_permalink()); ?>" title="<?php the_title_attribute(); ?>"> <?php the_title(); ?> </a> </h2> This way you're mixing HTML and PHP but it allows you to immediately output both, so that `the_title_attribute()` is outputting in the right spot and not before everything else is parsed. You can add the additional `esc_html__()` call wrapped within each set of PHP tags but it's not clear why those would be needed for fields like `the_permalink()`.
stackexchange-wordpress
{ "answer_score": 1, "question_score": 0, "tags": "escaping" }
How to count posts with specific arguments I'm wondering how I can request the amount of posts by passing certain arguments (you could see this as part of a "query"). See the example below. $args = [ "numberposts" => -1, "post_type" => "jobs", "s" => "developer", "tax_query" => ["taxonomy" => "IT", "field" => "slug"] ]; $posts = get_posts($args); $count = count($posts); I'm aware of the fact that the following function works perfectly for my case. However, it's extremely exhausting to execute. Instead of actually getting all posts within a query, I'm just looking for a function that just counts the posts with certain arguments. Please bare in mind that I'm passing on certain meta_queries and tax_queries which will make some queries to the database fairly hard on itself already. Hope someone can help.
The easiest way to optimize this query would be to add `'fields' => 'ids'` to the arguments. This way only ids of posts will be retrieved from DB (and usually that’s a big change). $args = [ 'numberposts' => -1, 'post_type' => 'jobs', 's' => 'developer', 'tax_query' => ['taxonomy' => 'IT', 'field' => 'slug'], 'fields' => 'ids' ]; $posts = get_posts($args); $count = count($posts); On the other hand you can use `WP_Query` instead of `get_posts`. This way you can set `posts_per_page` to 1, so only one ID will be retrieved and use `found_posts` field of WP_Query to get the total number of posts matching your criteria. $args = [ 'posts_per_page' => 1, 'post_type' => 'jobs', 's' => 'developer', 'tax_query' => ['taxonomy' => 'IT', 'field' => 'slug'], 'fields' => 'ids' ]; $query = new WP_Query($args); $count = $query->found_posts;
stackexchange-wordpress
{ "answer_score": 4, "question_score": 0, "tags": "wp query, get posts, count" }
update custom taxonomy with Ajax in edit.php file I created Custom Psot Type and Custom Taxonomy. I recover, for each CPT element its custom taxonomy. here is a screenshot: ![enter image description here]( now , i want update the coustom taxonomy for the CPT element with ajax without opening the post.php . is there a solution? help please thank you
i found a solution similar to mine Custom column for changing post status via ajax
stackexchange-wordpress
{ "answer_score": -1, "question_score": 0, "tags": "custom post types, custom taxonomy, ajax" }
Detecting embeded video format I need to get the video format from the shortcode. Example if i set my post meta "_video_format_embed" with `[video src=" /]` . how to get the video format of my shortcode? $video_embeded = get_post_meta(get_the_ID(), '_video_format_embed'); $video_format = '???'; // please help if('mp4' === $video_format){ //some code }
so you place your video inside a shortcode and then you can run a filter on that shortcode function. works like this (to be placed inside functions.php or some custom plugin): function so327822_wp_video_shortcode($output, $atts) { //get video ID by src $video_id = attachment_url_to_postid( $atts['src'] ); //get video meta $video_meta = wp_get_attachment_metadata( $video_id ); //uncomment next line, to view all meta //echo '<pre>' . print_r($video_meta, true) . '</pre>'; if ( $video_meta['fileformat'] === 'mp4' ) { //mess with $output here, if we have mp4 } //return return $output; } add_filter('wp_video_shortcode', 'so327822_wp_video_shortcode', 10, 2);
stackexchange-wordpress
{ "answer_score": 0, "question_score": 1, "tags": "shortcode, embed" }
How to change posts order on Category and Tag archives? WordPress by default order posts in descending order by date. But I want them to be in ascending order by date. How do I turn the order to ascending only for tags and category? I don't want blog post orders to change.
You can use `pre_get_posts` action to modify this order. Here's the code: function my_change_posts_order( $query ){ if ( ! is_admin() && ( is_category() || is_tag() ) && $query->is_main_query() ) { $query->set( 'order', 'ASC' ); } }; add_action( 'pre_get_posts', 'my_change_posts_order'); What we do here is: 1. We're adding our function that will modify params for WP_Queries 2. We make sure that it will change only main query (the one created by WordPress) and only on category and tag listings ( `is_category()` and `is_tag()`). 3. We change the order of posts for these pages by setting `order` to `ASC`
stackexchange-wordpress
{ "answer_score": 7, "question_score": 1, "tags": "wp query, loop, hooks, pre get posts" }
Use custom field value as href I created a custom field and would like to use its value as the href on a tag that would go on my footer. The custom field is on the Settings > General area of the dashboard and I used add_settings_field() in order to create it. So, for example, the value inserted in my custom field is "< and I would like that in my href. It would basically look like this: <a href="CUSTOM FIELD VALUE GOES HERE">Click Here</a> Is there any way to accomplish that?
To retrieve a value after using add_settings_field() you should use get_option(). So you could do something like this... $value = esc_html(get_option('option_name')); if ($value) { echo '<a href="' . $value . '">Click Here</a>'; } You just need to change `option_name` to your field name. The code will grab the value and if it isn't false echo the link. Also added the escaping. *Updated after OP gave more details
stackexchange-wordpress
{ "answer_score": -1, "question_score": 0, "tags": "custom field, footer" }
Where can I see all changes for a new WordPress version? Could someone tell me where I could find detailed information about what has beend changed/improved in a new WordPress major/minor version? Maybe some kind of changelog or something?
First of all you can follow WordPress Blog and its Releases category. Another great source of information on that is page with WordPress Versions on Codex \- here you can find info on every version - link to changelog (very useful - it contains list of changed files and links to trac tickets solved in this version) and to release article for that version on blog (mentioned in previous paragraph). For example article for 5.0.3 version: <
stackexchange-wordpress
{ "answer_score": 1, "question_score": 0, "tags": "updates, core" }
Strange glyphs code error Recently I've noticed that just above the web page logo, strange glyphs appeared. What might be the cause? How to get rid of these.
If there is anything printed above the logo, then in most cases it's caused by some errors in PHP. So somewhere in your theme or in one of plugins there is some bad code that is causing this. And these characters suggest that they're some badly converted UTF characters or some other characters that are not supported by your font. From my experience - such problem occurs when site gets infected and malicious code is working not entirely how its author wanted it to... So I would check your theme and then all other files of that site if they were modified and if they contain some code that doesn't look nice.
stackexchange-wordpress
{ "answer_score": 0, "question_score": 1, "tags": "errors, visual editor, coding standards" }
How to change how long items are kept in the trash? When the trash feature is enabled, the deleted posts are moved to trash and stored there for 30 days. And there is a schedule/wp_cron event that is responsible for removing these posts permanently after that time. Is there any easy way to change that time?
You can change that in `wp-config` (< define( 'EMPTY_TRASH_DAYS', 1 ); // Integer is the amount of days
stackexchange-wordpress
{ "answer_score": 4, "question_score": 2, "tags": "wp admin, hooks, wp config, configuration" }
Wp includes access control Everyone peoples can easily acess to my wp-includes how can i hide or not visible files to users can anybody help me regarding it this is my wordpress website link see everybody can see this <
Considering you got an Apache server, use this full code in the .htaccess file: # Block the include-only files. <IfModule mod_rewrite.c> RewriteEngine On RewriteBase / RewriteRule ^wp-admin/includes/ - [F,L] RewriteRule !^wp-includes/ - [S=3] RewriteRule ^wp-includes/[^/]+\.php$ - [F,L] RewriteRule ^wp-includes/js/tinymce/langs/.+\.php - [F,L] RewriteRule ^wp-includes/theme-compat/ - [F,L] </IfModule> # 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 As a bonus, I would also add this: <IfModule mod_autoindex.c> Options -Indexes </IfModule>
stackexchange-wordpress
{ "answer_score": 0, "question_score": 0, "tags": "wp query, css" }
Get post count for current custom taxonomy My site has a custom taxonomy called `series`. Underneath each post, I'm trying to display a specific div, but only if that post is in a series, and only if that series has more than one post. I feel like this should be possible with a simple if-statement, but I'm not sure how to evaluate the post count of the current post's first (because technically speaking one post could be in multiple series) `series` taxonomy. Any help would be greatly appreciated!
You can use `wp_get_post_terms( get_the_ID(), 'series' )` to obtain all terms associated with the current post. This function returns array of `WP_Term` objects and `WP_Term` has `count` property which can be used as condition.
stackexchange-wordpress
{ "answer_score": 1, "question_score": 0, "tags": "custom taxonomy" }
How to load custom post archives sub-pages with ajax? I'd like to keep the pagination links for /page/2/, /page/373/, etc but instead of changing the URL on the browser i want everything to load on the archive main page. Ideally all those paginated URLs should redirect to the first page of the archive. I don't want a "load more" button i want to keep the logic of pages but load them via ajax keeping url unchanged. How can i do this? Any help is appreciated.
you might use the `$.load` and `preventDefault()` from jQuery. Assugming that you have `.page-link` link class on each url in pagination and you have all the posts in the `#content` div following code can help you to load the posts in that div on that particular page. $("body").on("click", "a.page-link", function(e) { e.preventDefault(); $("#content").load($(this).attr("href") + " #content"); }); This will replace the current posts in that page with the new posts from that particular page. A look on your div structure might help me to write the complete code for you which can work on your site.
stackexchange-wordpress
{ "answer_score": 2, "question_score": 1, "tags": "custom post types, ajax, pagination" }
WooCommerce subscriptions give option of manual renewal on checkout I am trying to figure out how I can offer the option of manually renewing (automatic by default) a subscription on the checkout page. I would ideally like this to be a checkbox on the checkout page which is ticked by default saying 'automatically renew subscription'. I can't seem to find any information on doing this so any input will be greatly appreciated.
Having done something similar recently: Step 1: Add your checkbox as a custom checkout field (not covered here, you can easily find guides on how to do this). Step 2: When the user submits their order at checkout, look for the manual renewal value in the submitted checkout data, and set it as meta on the WooCommerce order. add_action('woocommerce_checkout_update_order_meta',function( $order_id) { if(!empty($_POST['custom_manual_renewal'])){ update_post_meta($order_id,'custom_manual_renewal',1); } }); Step 3: When your subscription is created shortly after the order, look for your piece of meta and maybe set the subscription to manual. add_action('woocommerce_checkout_subscription_created', function($subscription, $order){ if(get_post_meta($order->get_id(),'custom_manual_renewal',true)){ $subscription->update_manual(true); //set subscription to be manual renewal } },10,2);
stackexchange-wordpress
{ "answer_score": 0, "question_score": 0, "tags": "woocommerce offtopic" }
Is it possible to access Gutenbergs reusable blocks in CPT block templates? What I am trying to do is to use specific Reusable Blocks, that are editable by certain admins in the back end, within block templates for custom post types. So if you register a CTP or edit the capabilities of standard post types, you can use them like: function create_add_post_types() { register_post_type( 'product', array( 'public' => true, 'capability_type' => 'page', 'show_in_rest' => true, 'template' => array( array( 'core/heading', array( 'placeholder' => 'Füge eine Überschrift hinzu', 'content' => 'Projektname - Stadt, Land', 'level' => 1, ) ), ) ); } add_action( 'init', 'create_add_post_types' ); ..except that insteadt of a core block like the heading here a reusable block is called.
I actually found a solution myself by following the way a reusable block is registered in this stackexchange thread: Reusable blocks are all stored in/as **core/block** and this block has the attribute **ref** which carries the post id of that block. So, you can use array( 'core/block', array( 'ref' => [your block ID], ) ), and the ID of every registered block is visible via the URL of that block at **[your-wordpress]/wp-admin/edit.php?post_type=wp_block**
stackexchange-wordpress
{ "answer_score": 4, "question_score": 5, "tags": "themes, templates, block editor" }
How it it possible to disbale all WooCommerce scripts and styles, but keep wc-ajax=get_refreshed_fragments working? I disabled all styles and scripts for certain pages using the following code: remove_action( 'wp_enqueue_scripts', [ WC_Frontend_Scripts::class, 'load_scripts' ] ); remove_action( 'wp_print_scripts', [ WC_Frontend_Scripts::class, 'localize_printed_scripts' ], 5 ); remove_action( 'wp_print_footer_scripts', [ WC_Frontend_Scripts::class, 'localize_printed_scripts' ], 5 ); As the question implies, the only thing, which has now disappeared, I want to keep working is the XHR AJAX calls to `wc-ajax=get_refreshed_fragments`. Is there any way to do this?
If you look how that script is loaded in WC core 'wc-cart-fragments' => array( 'src' => self::get_asset_url( 'assets/js/frontend/cart-fragments' . $suffix . '.js' ), 'deps' => array( 'jquery', 'js-cookie' ), 'version' => WC_VERSION, ), You'll see the path to that script, as well as it's dependencies. rebuild that path and enqueue it yourself. FYI `$suffix` is set like this: $suffix = defined( 'SCRIPT_DEBUG' ) && SCRIPT_DEBUG ? '' : '.min';
stackexchange-wordpress
{ "answer_score": 1, "question_score": 0, "tags": "woocommerce offtopic" }
Excerpt using Read More Tag How do I get the excerpt of a post that is using a Read More Tag? The documentation states that I should use the `the_content` function, but I don't want that. I just want the text. Furthermore, I don't want the Read More link automatically inserted into the same `paragraph` tag - I just want the text, and I'll create my own Read More link. Essentially, I'm trying to print the excerpt of a post without the read more link. Can I do that?
You just need to set the first argument of `the_content()` to an empty string: <?php the_content( '' ); ?> If you don't pass an argument it will use the default, which is a link with the text "(more…)", but by passing an empty string, the empty string (i.e. nothing) gets displayed instead. If you want it in a variable, use `get_the_content( '' )` in the same way, but for formatting to match properly you'll need to apply the `the_content` filter: $excerpt = apply_filters( 'the_content', get_the_content( '' ) );
stackexchange-wordpress
{ "answer_score": 0, "question_score": 1, "tags": "excerpt, read more" }
Get id from metabox dropdown Im using Reusable Metaboxes (old but still works) and I created a metabox that allows the user to pick a post from a list of custom post types. Right now that works pretty well, I can see all the posts in a list and I pick one and save. The data I see when I call the_meta() shows me that the field is indeed saving the id of the post I called: episode_guestid: a:1:{i:0;s:2:"18";} But I don't know how to get the id (in this case 18 - and this needs to be dynamic depending on the chosen post) and use it to display things from that post: title, featured image, metaboxes content. Tried the "easiest one" with no success (so I will need help with figuring out how to display the metabox data from that post as well): $guestid = $post_meta_data['episode_guestid'][0]; ?> <h1> Featuring: <?php echo unserialize($guestid); ?> </h1> Hope someone can help me out with this one. Thanks!
`the_meta` is a very bare-bones method. The return value you're seeing is raw, unserialized data. WordPress uses PHP serialization to store complex values like `Array`s and `Object`s as a `string` value. Have a look at `get_post_meta`: $guest_id = get_post_meta( get_the_ID(), 'episode_guestid', true ); $guest_post = get_post( $guest_id[0] ); echo '<pre>'; print_r( $guest_post ); You should see the post you're looking for. Let me know if that doesn't work.
stackexchange-wordpress
{ "answer_score": 1, "question_score": 0, "tags": "custom post types, metabox, front end" }
Redirecting Pages That No Longer Exist -- But Could in the Future I have several 404 errors with a URL such as: myWebsite/tag/foo/page/4/. Page no longer exists because a few posts were deleted tagged as "foo." Which is better: 301 redirect that to myWebsite/tag/foo/page/1/? Or just 410 delete them? I'm thinking if I do a 301 redirect -- then add more posts tagged as "foo," a 4th page will exist but those will be redirected back to page 1. Or if I 410 delete page 4 and it later exists in the future, it won't be found. I'm confused.
This is a tricky one. The quick and dirty (but correct) solution is to use a `307` temporary redirect and then remove it when the page returns. This way your SEO will not suffer from the 404 errors and search engines will know that the page might come back. However, if this is something that will happen often, it might be worth while looking at how the theme manages pagination and utilizing `wp_redirect()` to handle the redirect dynamically. If you need help with the dynamic route please add a new question referencing your pagination setup.
stackexchange-wordpress
{ "answer_score": 0, "question_score": 1, "tags": "redirect, customization" }
How do i remove "Website" field from Wordpress comments i have two websites i use Wordpress comments on one website and jetpack comments on another. Both websites shows website column, how do i remove it to save my site from giving unwanted backlinks ?
**1\. Using Plugins to disable Website field from comments** There are many plugins available in the WordPress repository that remove the Website field from the blog comments. The most easy way is to install Remove Fields or Remove Comment Website/URL Box. < **2\. Editing the WordPress Files to remove the Website field from comments** * open functions.php file and add code. `add_filter('comment_form_default_fields', 'website_remove');` function website_remove($fields) { if(isset($fields['url'])) unset($fields['url']); return $fields; }
stackexchange-wordpress
{ "answer_score": 3, "question_score": 2, "tags": "comments" }
How can to use the players from the Media Widgets in the body of a post to play audio and video files I've been trying to use the `<audio>` tag to play MP3 files and the `<video>` tag to play MP4 files, both with the `controls` attribute, and they work fine, but it isn't possible to apply custom styles over them and they change from one browser to another. Basically, `<audio>` tag works like this: <audio controls loop> <source src="audio.mp3" type="audio/mpeg"> </audio> And the `<video>` tag like this: <video controls loop> <source src="video.mp4" type="video/mp4"> </video> So I realized the default audio player set to the new Media Widgets introduced in WordPress 4.8 have nice players and they could be enough and I'd like to borrow their properties to use inside the body of audio/video format posts. How can I achieve that?
While writting this question, I went further to be sure I wasn't asking something trivial and it seems I was. I realized the players of both the theme I used and those new WordPress widgets use the same `<div class>` called `.mejs-mediaelement` and then I realized it points to MediaElement.js indicated both in the Make WordPress blog post and the first Google result when we search for this name (I thought WordPress had its own workaround, but I was wrong). However, we don't need to install the plugin because, as Jacob Peattie explained in a comment below: > WordPress already has MediaElement.js built in and uses it for its audio and video players. Then, we just need to add the following shortcodes respectively in order to add audio and video files to our posts: `[audio src="mymedia.mp3"]` `[video src="mymedia.mp4" width="640" height="360"]` Then, it'll look just like the new Media Widgets because they do practically the same, but as a widget, of-course.
stackexchange-wordpress
{ "answer_score": -1, "question_score": 0, "tags": "posts, widgets, media" }
Woocommerce Single Product Tabs Got Duplicate I have just change the order of these lines of code for some changing in single product template. add_action( 'woocommerce_after_single_product_summary', 'woocommerce_upsell_display', 10 ); add_action( 'woocommerce_after_single_product_summary', 'woocommerce_output_product_data_tabs', 15 ); add_action( 'woocommerce_after_single_product_summary', 'woocommerce_output_related_products', 20 ); After toggling the numeric digit at the first two lines i am getting duplicate tabs. If i reorder them it will revert back to the default position. Kindly assist me what can i do. Thanks
Found a quick solution for this problem. Unable to remove action as Sally mentioned above with example.For me the display:none; is enough, i have remove the child div of summary class. See the code below: .summary.entry-summary div:nth-child(5) { display: none; } For me its 5th child maybe it will help others.
stackexchange-wordpress
{ "answer_score": 0, "question_score": 0, "tags": "plugin development, woocommerce offtopic" }
Author Date Function not working as expected I am trying to get whether the author has posted within the last 30 days but this returns TRUE even if the author hasn't posted within the last 30 days. <?php $args = array( 'post_type' => 'post', 'post_status' => 'publish', 'author' => get_current_user_id(), 'date_query' => array(array('after' => date('Y-m-d', strtotime('-30 days')), 'inclusive' => true,),) , 'fields' => 'ids',); $wp_posts = get_posts($args); if(count($wp_posts)) : ?> <div>Author posted within the last 30 days</div> <?php else : ?> <div>Author did not post within the last 30 days</div> <?php endif; ?> Not sure what I am doing wrong here.
Actually your function works as you described. I copied your function into a page template on my site without modifying it at all. I tested it with my main user, which has posted, and it said I had posted. Then I created a dummy user that has not posted. I tested the same page and it said I had not posted. I also posted a post backdated more than 30 days, and it still said I had not posted within the last 30 days. All of that is by design. A couple of points to keep in mind: * You aren't specifying in your query which type of post is being retrieved. Are you sure that the user you are testing with hasn't posted _any_ type of post? i.e. a custom post type, a page, a contact form via a plugin, etc. * Your code is also always checking the currently logged in user. Make sure that's what you want.
stackexchange-wordpress
{ "answer_score": 2, "question_score": 0, "tags": "functions, author" }