INSTRUCTION
stringlengths
11
999
RESPONSE
stringlengths
0
999
SOURCE
stringlengths
16
38
METADATA
dict
Not display an image of category of custom post $cats = array('taxonomy'=>'types'); $categories = get_categories($cats); foreach($categories as $category) { echo '<p>Category:'. $category->name.' </p> <br>'; echo '<p> Description:'. $category->description . '</p> <br>'; $term_id = $category->term_id; echo $term_id; $meta_image = wp_get_attachment_image($category->$term_id); echo $meta_image; ?> <img src="<?=$meta_image?>" alt="image"> <?php }
First of all `$category->$term_id` is wrong use `$category->term_id` I don't think `$category->$term_id` will give you the desired result For this you must have create some meta for the image in the backend. term_image_id = get_term_meta( $category->term_id, 'your-term-id', true ); Here the term id is `$category->term_id` and the term value is `your-term-id` Can you please check if that works or not?
stackexchange-wordpress
{ "answer_score": 0, "question_score": 0, "tags": "posts, customization" }
Wordpress Pods Custom Post Type - separate Media Upload folder for each custom Post Types I searched but unable to find the answer. I am using Pods Framework for creating custom post types in Wordpress. I want each user roles to have different media upload folder so like I have a post type 'local news' and another post type 'books' and two user roles like 'news editor' and 'book publisher'. So when news editor upload images in local news post type then it should not have access to all my images from uploads directory. and same with book publisher. So they can not see each others media and it will also be easy to manage images with separate folder for each post type. _How to achieve this ?_
WPBeginner appears to have an article that addresses what you are talking about. Failing that, you might Google search for "wordpress media access control". I found several plugins that might work for you.
stackexchange-wordpress
{ "answer_score": 0, "question_score": 0, "tags": "posts, customization" }
WordPress and WooCommerce - How many products are too many? I have imported about 12,000 WooCommerce products into WordPress. I think my site isn't working anymore because of that. Is 12,000 products really to much for WordPress to handle?
Nope, that is not the issue with your website, according to the WooCommerce FAQ: **What is the maximum WooCommerce can handle?** > Sky is the limit. We’ve seen instances of shops with 100,000+ products listed, handling thousands of transactions per minute. In those cases, they had great hosting support and their own developer team focused on optimization.
stackexchange-wordpress
{ "answer_score": 5, "question_score": 0, "tags": "woocommerce offtopic, server load" }
$wpdb->prepare with LIKE returning blank array instead of rows I trying to select data from a table using LIKE and wildcards. I tried basically everything. Here'is the last code according to WordPress documentation: <?php global $wpdb; $table_name = $wpdb->prefix . 'city'; $city= 'New York'; $city = $wpdb->esc_like( $city ); $city = '%' . $city . '%'; $prep = $wpdb->prepare(" SELECT * FROM {$table_name} LIKE name=%s ", $city); echo $prep . '<br><br>'; $rowsSelected = $wpdb->query($prep); print_r($wpdb->last_result); $wpdb->flush(); The output: SELECT * FROM wp_city LIKE name='{7fd8d56e635a959f67faccf3bbff451d20c9e3acfb7bb1a69dc35208e9a29109}New York{7fd8d56e635a959f67faccf3bbff451d20c9e3acfb7bb1a69dc35208e9a29109}' Array ( ) The issue: I always get an empty array WordPress version: 5.2.2
Your SQL doesn't look right. It should be more like $prep = $wpdb->prepare( "SELECT * FROM {$table_name} WHERE name LIKE '%s'", $city );
stackexchange-wordpress
{ "answer_score": 2, "question_score": 0, "tags": "sql, wpdb" }
Can I add the post featured image to a specific RSS feed? I'm currently using the following code: function featuredtoRSS($content) { global $post; if ( has_post_thumbnail( $post->ID ) ){ $content = '<div>' . get_the_post_thumbnail( $post->ID, 'medium', array( 'style' => 'margin-bottom: 15px;' ) ) . '</div>' . $content; } return $content; } add_filter('the_excerpt_rss', 'featuredtoRSS'); add_filter('the_content_feed', 'featuredtoRSS'); Which does work, but I'm running a few MailChimp RSS emails campaigns and am needing one RSS feed to show the featured image (articles feed) and one where I don't want to show the featured image. My thought is to do this by category, possibly? Let me know if more clarification is needed! Thanks!
WPBeginner has a nice article " How to Create Custom RSS Feeds in WordPress" that addresses this from a manageable perspective. They cover creating custom feeds, and using theme templates to customize what your feeds publish. Take a look.
stackexchange-wordpress
{ "answer_score": 1, "question_score": 0, "tags": "php, rss, feed" }
How to create author profile showcase in wordpress I am looking at showcasing author profiles like here: < I have been looking at plugins available but nothing gets close to this layout. If I have to develop this in wordpress, what should be the way forward? *I have only worked with ready made Themes so far and haven't actually developed new functionality in wordpress. It would be great to get a direction on this.
You might try the Ultimate Member – User Profile & Membership plugin. I haven't used their user profile layouts, but they promise to deliver exactly what you are asking for.
stackexchange-wordpress
{ "answer_score": 1, "question_score": 0, "tags": "plugins" }
When i try to open archive pages i get a 404 error i do not create any new CPT, simply want to open WP standard archive pages like category (eg. < but when i try to do that i got a 404 error. Can you help me?
Probably you have to go to `Permalinks > click "Save Permalinks"` and refresh that archive page to see if it solved. If not, then maybe you are using some plugin that caused the problem? deactivate all plugins and re-save permalinks and check that archive page again.
stackexchange-wordpress
{ "answer_score": 1, "question_score": 1, "tags": "archives" }
Trying to create a mouseover effect in html using Gutenberg editor I am trying to create a mouseover effect in html on a content block in the Wordpress code editor. I want an icon to change color on mouseover and change back on mouseout so I'm referencing two different colored icon pictures. I'm also not sure what best practices are for spacing/indent; sorry if this is messy or hard to read. Here is the code I'm using to try to accomplish this: HTML <!-- wp:image {"id":1111} --> <figure class="wp-block-image"><img src=" alt="alttext" class="wp-image-1111"/></figure> <!-- /wp:image -->
You were very close. You just had a single-quote swapped with a double-quote after the onmouseover. <figure class="wp-block-image"> <img src=" onmouseover="this.src=' onmouseout="this.src=' alt="alttext" class="wp-image-1111"/> </figure> I usually place semi-colons after the single-quotes to make it easier to tell when your quotes are balanced, whether Javascript requires it, or not.
stackexchange-wordpress
{ "answer_score": 1, "question_score": 1, "tags": "images, html, block editor" }
how to load the comment template from a plugin I want to create custom design for the comments. `comments_template()` will load the default `\comments.php`. i have a file inside my plugin `commentsnew.php` how can i use this file for `comments_template()`? file is getting loaded relative to theme directory. `apply_filters( 'comments_template', string $theme_template )` this completely overrides the template but don't want a complete override but apply only if used.
You can use the `comments_template` filter to alter which file your CPT will use for comments. function wpse_plugin_comment_template( $comment_template ) { global $post; if ( !( is_singular() && ( have_comments() || 'open' == $post->comment_status ) ) ) { // leave the standard comments template for standard post types return; } if($post->post_type == 'business'){ // assuming there is a post type called business // This is where you would use your commentsnew.php, or review.php return dirname(__FILE__) . '/review.php'; } } // throw this into your plugin or your functions.php file to define the custom comments template. add_filter( "comments_template", "wpse_plugin_comment_template" );
stackexchange-wordpress
{ "answer_score": 1, "question_score": 0, "tags": "plugin development, wp query, comments, comment form" }
Creating a return url for getting data from external api I am working on a plugin with a payment system. I need to provide a return url for the payment gateway in order to receive its answers. I don't want to create a specific page but to have a kind of listener to do the treatments according to the return and redirect to a page of success or failure. So, i need some suggestions. Thanks.
You could register a rest route (ref: < In your case, something like this would do the trick: register_rest_route( 'your-plugin/v1', '/payments/(?P<trans_id>\d+)(?:/(?P<amount>\d+))?', array( 'methods' => 'GET', 'callback' => array( $this, 'your_callback_function'), 'args' => array( 'trans_id' => array( 'validate_callback' => function($param, $request, $key) { return is_numeric( $param ); } ), 'amount' => array( 'validate_callback' => function($param, $request, $key) { return is_numeric( $param ); } ), ), ) ); Figure out all of your parameters, setup validation here and then write yourself a callback function to do the actual work. Wordpress is moving down this path to replace the old admin-ajax api, and it's pretty easy to work with. More info: <
stackexchange-wordpress
{ "answer_score": 0, "question_score": 0, "tags": "plugin development, redirect, urls" }
Check if a filter or function has been already been called Is there a way in WordPress to check, on a screen load, if a filter has been called or a function has run? I seem to recall some way to do that, but don't recall the specifics. A filter is being called 3 times during a page load and I want to check if it has already been called before I run various db intensive code again. My questions is not specific to `the_content`, but for example: add_filter( 'the_content', 'asdf_the_content', 99, 1 ); function asdf_the_content( $content ) { // check if the_content has already been // filtered by some other function $content = ucwords( $content ); return $content; }
You can use a static variable to achieve this: add_filter( 'the_content', 'asdf_the_content', 99, 1 ); function asdf_the_content( $content ) { static $has_run = false; if ( $has_run ) { return $content; } $has_run = true; // check if the_content has already been // filtered by some other function $content = ucwords( $content ); return $content; } The `$has_run` variable will be `false` on the first run, and subsequent runs it will be `true` and the code will not continue. Static variables like this inside a function maintain their values during each execution, instead of initializing like normal variables. Another example: function add_one() { static $total = 0; $total++; echo $total; } add_one(); // 1 add_one(); // 2 add_one(); // 3
stackexchange-wordpress
{ "answer_score": 4, "question_score": 5, "tags": "filters" }
Menu with sub-items but without link while using WP you can change your main menu pretty easy. Still, when I want to create a new menu button, I have to give it a link to some article, category etc. Is there a way to avoid it? In wanted to made a menu with some buttons with sub-items, for example: About us > Team members > Contact I would like to make "About us" without being a link to anything - just a folder for "Team members" and "Contact". Is it possible?
Yes, you can add a custom link with # instead of the page into the menu ![custom link]( See in the attached screenshot
stackexchange-wordpress
{ "answer_score": 0, "question_score": 0, "tags": "menus, buttons, add submenu page" }
How can I fetch user registration age How can I fetch the user registration age? Like for example user A registered 7 days ago, user B 10 days ago etc. In my current project, I have this requirement where there are set of tutorial videos which based on the age of user registration videos should be open to access every week. > For example, Video 1 can be accessed on the first day of user registration and Video 2 will be accessible only after 7 days of his registration Video 3 after 14 days etc the same for all the videos. I cannot restrict this manually and make it accessible after every week because this should be depended on EACH USER registration age and not overall, I need some inputs like ways to fetch user registration age so that I have some jQuery code in mind to make video links accessible.
Solved the above task, posting the answer here so that someone can use the code I added this code in functions.php function is_user_video_perweek( $reg_days_ago ) { $currentuser = wp_get_current_user(); return ( isset( $currentuser->data->user_registered ) && strtotime( $currentuser->data->user_registered ) < strtotime( sprintf( '-%d days', $reg_days_ago ) ) ); } and then in footer.php I called this function and wrote conditions to disable links using javascript example <?php if( is_user_video_perweek( 84 ) ) { ?> <script type="text/javascript"> jQuery(".page-id-1572 #allvideos a").css("pointer-events", "auto"); </script> <?php }elseif( is_user_video_perweek( 0 ) ){?> <script type="text/javascript"> jQuery(".page-id-1572 #allvideos a").css("pointer-events", "none"); </script> <?php } ?>
stackexchange-wordpress
{ "answer_score": 0, "question_score": 0, "tags": "user registration, content restriction" }
start_lvl on Walker is not working I'm creating a custom Walker to my menu, my code is like this: <?php class My_Walker extends Walker { function start_lvl( &$output, $depth = 0, $args = array() ) { $output .= "<nav>"; } function end_lvl( &$output, $depth = 0, $args = array() ) { $output .= "</nav>"; } function start_el( &$output, $object, $depth = 0, $args = array(), $current_object_id = 0 ) { $output .= "<li>My Item</li>"; //This is just a sample <li> } } The `start_el` is working fine, but `start_lvl` and `end_lvl` is not working at all. The rendered HTML is like this: ![list code sample]( Why is my `start_lvl` and `end_lvl` not working?
Your menu doesn't appear to have any levels. `start_lvl` and `end_lvl` are used for the _sub_ -menu wrappers. The outer wrapper for the menu, the `<ul`> is defined by the `items_wrap` argument of `wp_nav_menu()`: wp_nav_menu( [ 'walker' => new My_Walker(), 'items_wrap' => '<nav id="%1$s" class="%2$s">%3$s</nav>', ] );
stackexchange-wordpress
{ "answer_score": 5, "question_score": 1, "tags": "menus, walker" }
PHP file won't work in wordpress folder, but works in another virtual host So basically I made a php file that is called with two arguments (order total and order number) and it spits out a png with an EPC QR Code (so people just scan it and their banking app fills in all the details). This file works in an empty virtual host, but it won't work when I put it anywhere in a wordpress directory/virtual host. Is there some setting somewhere that is keeping non-wordpress php files from executing?
Yes. The default WordPress .htaccess file. Without edits, all calls are redirected to `index.php`. Your best bet is to pass the call through WordPress as a custom plugin. This answer deals with setting up a REST endpoint. Of course, that means returning JSON which might not be exactly what you are looking for. Another approach might be to edit the `.htaccess` file. Something like this, near the top: RewriteRule my-qr-code.php$ - [L] This tells the server that in this case, if the file matches, we are done. That solution comes from a StackOverflow question.
stackexchange-wordpress
{ "answer_score": 0, "question_score": 1, "tags": "php" }
WP-CLI update date and time format I'm new to WP-CLI. After a lot of Googling and searching in this forum, I haven't found out which is the command to update both date and time formats. wp option update...... Thanks for any help! Regards
The wp-cli command structure would be: wp option update timezone_string "American/New_York" So: 1. _option_ to act on a WordPress option 2. _update_ to update the option 3. the _option name_ , in this case 'timezone_string' 4. the new _value_ , in this case 'American/New_York' Items 3 and 4 are defined by WordPress, a plugin, or other custom code. Number 4, the value may have only a limited number of valid values. In this case, something other than a standard timezone would cause problems. Generally speaking, I update the timezone, time format and start of week to Sunday. wp option update timezone_string "America/New_York" wp option update time_format "g:i A" wp option update start_of_week 0 So research your basic WordPress options to determine the option name and the valid values, then structure your command line appropriately.
stackexchange-wordpress
{ "answer_score": 6, "question_score": 5, "tags": "wp cli" }
Cannot add javascript to footer Im trying to paste my javascript into footer and cant figure out. function js_enqueue_search(){ wp_register_script("search", get_stylesheet_directory_uri() . "/js/search.js", "", wp_get_theme()->get("Version"), true); wp_localize_script('search', 'search_ajax', array("ajaxurl" =>admin_url("admin-ajax.php"))); } add_action("wp_enqueue_scripts", "js_enqueue_search");
Your're missing the call to `wp_enqueue_script( 'search' );` after it's registered. function js_enqueue_search() { wp_register_script( 'search', get_stylesheet_directory_uri() . '/js/search.js', '', wp_get_theme()->get( 'Version' ), true ); wp_enqueue_script( 'search' ); wp_localize_script('search', 'search_ajax', array( 'ajaxurl' =>admin_url( 'admin-ajax.php' ))); } add_action( 'wp_enqueue_scripts', 'js_enqueue_search' );
stackexchange-wordpress
{ "answer_score": 1, "question_score": 1, "tags": "php" }
gettint error 400 with AJAX So hello I'm getting error 400. Here is my PHP and JS path to file is right. PHP add_action("wp_enqueue_scripts", "js_enqueue_search"); function js_enqueue_search(){ wp_register_script("search", get_stylesheet_directory_uri() . "/js/search.js", "", wp_get_theme()->get("Version"), true); wp_enqueue_script("search"); wp_localize_script("search","search_x", array("ajaxurl" => admin_url("admin-ajax.php"))); } add_action("wp_ajax_nopriv_search_data", "search_data"); add_action("wp_ajax_search_data", "search_data"); function search_data(){ echo "test"; wp_die(); } JS let ajax = new XMLHttpRequest(); ajax.open("GET", search_x.ajaxurl, true); ajax.send(); ajax.onreadystatechange = function() { if (this.readyState == 4 && this.status == 200) { console.log(this.ajax); } };
i can't see the `action` parameter in your code it should be: let ajax = new XMLHttpRequest(); ajax.open("GET", search_x.ajaxurl + '?action=search_data', true); ajax.send(); ajax.onreadystatechange = function() { if (this.readyState == 4 && this.status == 200) { console.log(this.ajax); } }; see this reference about action parameter <
stackexchange-wordpress
{ "answer_score": 0, "question_score": 0, "tags": "php, javascript" }
jetpack suddendly stopped working Suddendly Jetpack stopped working on my (multisite) blog. I tried to disconnect and reconnect it, but now a timeout message appears: The Jetpack server was unable to communicate with your site [IXR -32300: transport error: http_request_failed cURL error 28: Connection timed out after 10001 milliseconds] Blog is reachable, and I can (manually) add other plugins giving username and password to Wordpress. I changed theme and removed plugins, with no effect. My only doubt is that the server runs a very old version of PHP (5.6.40), but documentation says that it supports from 5.6.20. What could I try?
I had a similar issue last year (minus the old php version) and they modified some firewall or something. Try contacting jetpack support: <
stackexchange-wordpress
{ "answer_score": 1, "question_score": 1, "tags": "plugin jetpack" }
WordPress 403 issue when passing parameters in the URL I have been experiencing a 403 error when passing parameters in the URL of a WordPress website. Has anyone else experienced this and have a solution? The url being passed is {{website_url}}/contact-us?enquiry_type=1 However, when removing the parameter, I dont get the 403 error. Your input would be much appreciated. ![enter image description here](
This error is generated by the Cerber Security Plugin. You can add an exception on 'Antispam' under the WP Cerber menu, 'Adjust Antispam engine', 'Query whitelist'. You probably want {\/contact-us\?enquiry_type=\d+} for a regular expression to match any numeric enquiry_type value. The relevant documentation is here: Configuring exceptions for the antispam engine.
stackexchange-wordpress
{ "answer_score": 2, "question_score": 2, "tags": "permalinks" }
Pass custom Checkout field value to Stripe gateway in WooCommerce I have added a custom checkout field to my WooCommerce web site. I have added and enabled Stripe plugin, as payment gateway… Is there a way to have this custom fields value sent as data to Stripe payment gateway? I have searched everywhere but couldn't find anything.
You can use `wc_stripe_payment_metadata` dedicated filter hook to add (pass) some custom meta data to Stripe gateway, this way: add_filter( 'wc_stripe_payment_metadata', 'stripe_payment_metadata_filter_callback', 10, 3 ); function stripe_payment_metadata_filter_callback( $metadata, $order, $prepared_source ) { // Here below define your custom field meta key (as it's saved in wp_postmeta DB table) $metadata = 'custom_meta_key'; $metadata[ __( 'Custom Label Text (or meta key)', 'woocommerce-gateway-stripe' ) ] = $order->get_meta($meta_key); return $metadata; } Code goes in functions.php file of your active child theme (or active theme). It should work. * * * Related threads: * WooCommerce Stripe official documentation - Filter Hooks section * WooCommerce Stripe: Add Custom MetaData _(April 2018)_ * Send Variation options to stripe as metadata with WooCommerce _(May 2018)_
stackexchange-wordpress
{ "answer_score": 5, "question_score": 2, "tags": "woocommerce offtopic" }
What is the $context in remove_meta_box function? I use the remove_meta_box function to remove the area I don`t want to display in the dashboard. But I can`t figure out what is the $context ? remove_meta_box( $id, $page, $context ) `$context` has three string to choose **side , normal , advanced** what is difference among these three??
The context within the screen IS where the boxes should display. Available contexts vary from screen to screen. Post edit screen contexts include 'normal', 'side', and 'advanced'. Comments screen contexts include 'normal' and 'side'. Menus meta boxes (accordion sections) all use the 'side' context. Global default is 'advanced'. So it is the place you are removing the box from. <
stackexchange-wordpress
{ "answer_score": 2, "question_score": 2, "tags": "functions" }
`save_post` hook called on inserting new post from front end I have a front end form which creates a new post in a custom post type and adds some meta data to the post. I am submitting the form by checking for `$_POST` values in the same page in which form is created. if( isset($_POST['save_form']) ){ $post_info = ''; // Set values to variables $post_id = wp_insert_post( $post_info ); add_post_meta($post_id, 'my_key', $form_field, true); } Recently i have found that `save_post_{post_type}` hook is fired whenever i submit this form. So all the fields in the front end form are available inside the callback function. Is this default or have i done something wrong ? Should i change the saving method since posted values are available in `save_post_{post_type}` hook.
Yes it is the default and yes you should be doing your work inside the save_post_{post_type} action. That's exactly what it is there for and is its intended use. Be careful, though, as this action is called **every time** the post is "saved" (created _or_ updated)!
stackexchange-wordpress
{ "answer_score": 1, "question_score": 0, "tags": "custom post types" }
How to deal with Slow HTTP POST (slowloris) vulnerability I'm using WordPress Version 5.2.2 I've been asked to implement changes highlighted as required by a security scan, the problem is I have little access (none in fact I think) to the webserver configuration, which makes some changes, difficult. Is it possible for me to deal with Slow HTTP POST vulnerabilities in WordPress, (< without changing the server configuration?
No, there is nothing you can do if you are unable to modify the HTTP server behavior. The reason is that the HTTP server receives and processes the initial request and then hands it off to PHP. PHP then processes the request and hands the response back to the HTTP server, which then sends it back to the client. PHP does have a built-in HTTP server but it is HIGHLY unlikely that Kinsta is using it and it does not appear to offer any kind of configuration and moreover, is not recommended for production or even public use. See < for details.
stackexchange-wordpress
{ "answer_score": 1, "question_score": 0, "tags": "plugins, security" }
How do I ensure I can loop through every enqueued script and CSS? I'm on a bit of an efficiency drive. To this end, I would like to check all the scripts and CSS that get enqueued on my multisite setup. I plan to check that they are offloaded to public CDNs if available or some other private static site if I have set that up, while also ensuring there are no duplicates. Where I am currently stuck (aside from wondering if the extra work actually will save load times at all) is what hook I can use to make sure all the enqueing is done when my script kicks in. What hook or filter should I use for this purpose? (Feel free to educate me and any future searchers about anything else I/we should know when attempting this).
In terms of the basics, I have learned that there are two actions to hook - `wp_print_scripts` and `wp_print_styles` which I understand are called just before they are then added to the header. add_action( 'wp_print_scripts', 'my_list_scripts' ); function my_list_scripts() { global $wp_scripts; $enqueued_scripts = array(); foreach( $wp_scripts->queue as $handle ) { // do something clever } } add_action( 'wp_print_styles', 'my_list_styles' ); function my_list_styles() { global $wp_styles; $enqueued_styles = array(); foreach( $wp_styles->queue as $handle ) { // do something clever } }
stackexchange-wordpress
{ "answer_score": 0, "question_score": 0, "tags": "plugin development, multisite, hooks, wp enqueue script, wp enqueue style" }
Does get_post function counts as view? I have a php file that is working outside wordpress's plugin and template system, and I am calling get_post to get the post's content. Does it count as a post view?
WordPress doesn't count post views. So no. Nothing counts as a post view. If you're using a plugin or service that counts post views, then it would depend on that plugin or service, and how it measures views. You'd need to ask its author, but I feel safe saying that none of them would use `get_post()` to count views.
stackexchange-wordpress
{ "answer_score": 1, "question_score": 0, "tags": "php" }
How do I know if my WP Theme is using infamous TimThumb? Is there a way to know if my current WordPress theme is using the infamous TimThumb plugin?
One option is to install a security plugin. Most scan for Tim Thumb throughout your whole file structure, including themes (and will also search for many other types of vulnerabilities if you've been hacked, as your "hacked" tag indicates). You can also search for files named "timthumb" in your theme directory, or search for the phrase "timthumb" in all files on your site. It helps if you have a local copy and a good editor that will search through files.
stackexchange-wordpress
{ "answer_score": 1, "question_score": 0, "tags": "hacked" }
403 forbidden access to my whole site Yesterday I tried to add some lines of code to my `functions.php` and suddenly the whole site throw 403 forbidden error. Both frontend/admin. Asked my hosting provider ( SiteGround ) and they said it is blocked because of security reasons as far as I understood. How can I check for malwares if I can't access my admin panel to install plugin for this. Also downloaded the files on my local server ( I am using LAMP stack on Ubuntu 18 ) and when I try to reach my local domain it redirects me to the site again with 403 forbidden error. What I tried to add as code is : function test() { echo "TEST"; } add_action("test", "test") After that I have deleted it through FTP. Hope I explained the situtation clearly. If you need more info to give me some advice will provide it immediately. Thank you!
You need to look at all files via your hosting File Manager (or FTP). Look for any code that shouldn't be there. See my answer to Coinhive Malware on WordPress websites , of things to check. And here's the process I use to clean up hacked WP sites: < . Basically: change credentials on everything; look at all file contents for hacked code; reinstall everything from known good/original source; reinstall latest WP; and more.
stackexchange-wordpress
{ "answer_score": 1, "question_score": 0, "tags": "errors" }
Select multiple categories with is_tax i have a good function for exclude out of stock products from category. The problem is i want exclude for more than one category (really i want show only in one category, but i think this is the way. If someones know how show only in one category...). Here is the code. thanks! /* Hyde out of stock product specific category */ add_filter( 'pre_get_posts', 'hide_out_of_stock_from_cat' ); function hide_out_of_stock_from_cat( $query ) { if ( $query->is_tax( 'product_cat', 15 ) && $query->is_main_query() ) { $query->set( 'meta_query', array(array( 'key' => '_stock_status', 'value' => 'outofstock', 'compare' => 'NOT IN' ))); } }
Thanks to @SallyCJ for the correct answer -- you can supply an _array of category IDs/slugs/names_ to `is_tax()` to check for multiple categories. Here is the correct code: /* Hyde out of stock product specific category */ add_filter( 'pre_get_posts', 'hide_out_of_stock_from_cat' ); function hide_out_of_stock_from_cat( $query ) { if ( $query->is_tax( 'product_cat', array( 15, 16, 18, 19, 20, 21, 22, 23, 24, 59, 60, 62, 63, 66 ) ) && $query->is_main_query() ) { $query->set( 'meta_query', array(array( 'key' => '_stock_status', 'value' => 'outofstock', 'compare' => 'NOT IN' ))); } }
stackexchange-wordpress
{ "answer_score": 0, "question_score": 0, "tags": "wp query, woocommerce offtopic, tax query" }
how to pass args for archive.php query? I am trying to pass args to archive.php so that I can order the posts, set the number of posts, etc.. but the query is done like this <?php if (have_posts()): ?> <?php while (have_posts()): the_post();?> if it was`new \WP_Query($args);` i was able to pass the args here but this can't be done in archive.php template?
The `pre_get_posts` hook can be used to modify queries before they're run. You can use `$query->set()` to set arguments on the `WP_Query` object, and `$query->is_main_query()` in the callback to limit your changes to the main query: add_action( 'pre_get_posts', function( $query ) { if ( ! is_admin() && $query->is_main_query() ) { $query->set( 'posts_per_page', 12 ); } } ); You can't target specific _templates_ , but if you want the change to only affect archives, you can use `$query->is_archive()`, which will be true for date, taxonomy and post type archives, or if you only want to apply the changes to the category archives, you can use `$query->is_category()`. Many of the normal conditional functions are available as methods for checking the current query.
stackexchange-wordpress
{ "answer_score": 0, "question_score": 0, "tags": "custom post types, wp query, templates, archives, archive template" }
wp_options is GB in size How can I find what options or plugins are taking up all that size? It's not transients because after deleting all it's still 13GB. `SELECT option_name, option_value FROM hihgv_options WHERE autoload = 'yes'` Returns 833 rows in 0.141 sec `SELECT SUM(LENGTH(option_value)) as autoload_size FROM hihgv_options WHERE autoload='yes';` returns 670,540 * * * At one point it was 13GB and went down to MB when I move everything from the My Custom Functions plugin to the child theme's functions.php file.
After executing these: [root@shop ~]# mysqlcheck -p -c wordpress hihgv_options wordpress.hihgv_options OK [root@shop ~]# mysqlcheck -p -o wordpress hihgv_options wordpress.hihgv_options note : Table does not support optimize, doing recreate + analyze instead status : OK [root@shop ~]# mysqlcheck -p -a wordpress hihgv_options wordpress.hihgv_options OK Size is down to 1.6MB, not sure if it was optimize because I've done that before from HeidiSQL with no change at all. Edit: Also the SQL queries from OP still return the same numbers. Edit 2: Just did it again, after executing: ` [root@shop wordpress]# mysqlcheck -p -o wordpress wp_options note : Table does not support optimize, doing recreate + analyze instead status : OK ` It went from 3.9GB to 10MB. If anyone knows exactly why I'd appreciate an explanation.
stackexchange-wordpress
{ "answer_score": 1, "question_score": 2, "tags": "database" }
How do you output an unknown number of images in a custom post type with desired markup? I'm working on a theme that will have an image gallery within a custom post type. I'm able to insert them into the post (using Advanced Custom Fields and embedding them in a WYSIWYG box) but I was wondering if there was a cleaner way to do it, such as using the image uploader field of ACF and an option to (e.g.) ADD ANOTHER. Then I would like the images to appear wrapped in DIVs and with some specific markup to get them to play nicely with the Owl Carousel code I've set up. I don't know how many images each entry will have. Any help would be very appreciated and I'd be more than happy to share any further info! Cheers, M
@RiddleMeThis answer is great, but I found a free option that allowed me to add repeater fields whilst simultaneously using Advanced Custom Fields: WCK - Custom Fields and Custom Post Types Creator The free version is very handy with the repeater field.
stackexchange-wordpress
{ "answer_score": 0, "question_score": 0, "tags": "custom post types, custom field, images, loop" }
TinyMCE Visual Blocks plugin set Show blocks option for all users I want the Show blocks feature of the TinyMCE Visual Blocks Plugin to be activated for all users. I can activate the Show blocks feature under the View menu dropdown manually. See picture. This activates it for the current user. How can I activate the feature for all users? Can it be done via the tiny mce before init hook similar to setting visualblocks_default_state ? ![enter image description here]( < <
Just add this code to `functions.php` of your theme and then "View" --> "Show blocks" will always be enabled immediately when the page loads if( !function_exists('custom_settings_tinymce') ){ function custom_settings_tinymce($init) { $init['visualblocks_default_state'] = true; return $init; } add_filter('tiny_mce_before_init', 'custom_settings_tinymce' ); }
stackexchange-wordpress
{ "answer_score": 1, "question_score": 1, "tags": "tinymce, visual editor, plugin tinymce" }
Strange multisite issue where all sites return same id with get_current_site() I'm trying to add some code based on which multisite is shown. However for both the main site and sub-domains it always shows the ID as 1. I've put $current_site = get_current_site(); var_dump($current_site); in both the header.php and index.php and they both output the same for every sub-domain: object(WP_Network)[275] private 'id' => int 1 public 'domain' => string '...' (length=16) public 'path' => string '/' (length=1) private 'blog_id' => int 1 public 'cookie_domain' => string '...' (length=16) public 'site_name' => string '...' (length=19) Has anyone else ran into this issue and know of a way to get the correct current id?
When Multisite was first rolled into core (from a project call "multi-user", which is why you'll sometimes see references to "mu-*"), the terminology was that you'd run a **site** of **blogs**. Now we refer to a **network** of **sites** , but because the functions had all already been named, `get_current_site()` gets the current **network**. You'll need to use `get_current_blog_id()` to get the current **site** 's ID, or `get_bloginfo()` or `get_blog_details()` for more detailed data on the current site. ## Reference * Note on `get_current_site`
stackexchange-wordpress
{ "answer_score": 3, "question_score": 1, "tags": "multisite" }
`<!--:en-->` Language notation in the post content Can someone tell mich which plugin usually handles the following notations, used to translate posts? <!--:en-->english text<!--:--> <!--:es-->spanish text<!--:--> Any way to get the posts translated using these tags is appreciated.
This is the notation of the (pretty old) Plugin qtranslate. It was abandoned way back and replaced by mqtranslate and later qtranslate-x, which at this point are also abandoned. You can however convert your content to be used with wp multilang, which works with gutenberg, by replacing the `<!--:lang-->` tags with kinda shortcodes [:lang]. So for the english text you would use [:en]English Text[:]. It would be even better if you would put all languages within a post into the same language "shortcodes" instead of "opening" one language, closing it, and "opening" the next language. Like this: [:en]English Text[:es]Spanish Text[:]
stackexchange-wordpress
{ "answer_score": 1, "question_score": 0, "tags": "tags, translation" }
How to check if feed URL was requested? I'm writing a plugin to block some pages to anonymous users on my site. I already blocked some pages but I can't get to identify the feed page `my-wordpress-site.com/feed`. I've tried: * `$GLOBALS['pagenow'] == 'feed'` * `is_feed()` * `is_page('feed')` * checking on `$_SERVER['REQUEST_URI']` and `$_SERVER['PATH_INFO']` Any ideas on how to achieve that?
You have not specified exactly when your code runs but you can hook into "request" to check the requested page: add_filter( 'request', function( $request ){ if( isset( $request['feed'] ) ){ //This is a feed request } return $request; }); When the requested page is a feed `$request`, which is an array of query variables, will contain an item called "feed" which is set with the name of the feed like "rss" for example. <
stackexchange-wordpress
{ "answer_score": 7, "question_score": 4, "tags": "php, pages, urls, feed" }
Wrap the 2 firsts words of title with a <Span> I would like to enclose the 2 first word of title inside a to get the following result: TOP 5 of best photos I tried using the code below, but it returns only the first word. How can i do to select 2 words? Thank you function add_label_to_post_title( $title = '' ) { if(trim($title) != "") { $ARR_title = explode(" ", $title); if(sizeof($ARR_title) > 1 ) { $first_word = "<span>".$ARR_title['0']."</span> "; unset($ARR_title['0']); return $first_word. implode(" ", $ARR_title); } else { return "{$title}"; } } return $title; } add_filter( 'the_title', 'add_label_to_post_title' );
You can do that like this: function add_label_to_post_title( $title = '' ) { global $post; if( 'post' == $post->post_type && trim( $title ) != "" ){ $title_words = explode( " ", $title ); $word_count = count( $title_words ); //Sets how many words should be wrapped $words_to_wrap = 2; $last_word_index = $word_count > $words_to_wrap ? $words_to_wrap - 1 : $word_count - 1; $title_words[0] = '<span>' . $title_words[0]; $title_words[ $last_word_index ] = $title_words[ $last_word_index ] . '</span>'; $title = implode( ' ', $title_words ); } return $title; } add_filter( 'the_title', 'add_label_to_post_title' ); You can change the value of `$words_to_wrap` to choose how many words should be wrapped in the span element. If a title has less words than `$words_to_wrap` value it would wrap only the available ones.
stackexchange-wordpress
{ "answer_score": 0, "question_score": 0, "tags": "wp title" }
How can I access core/paragraph textColor in a block template I am trying to set the default textColor of an Innerblocks => paragraph in my Gutenberg block plugin. The problem seems to be that placeholder is an attribute but textColor is passed as a prop < Wondering if anyone has figured out how to set this. Or if it is not possible. The documentation does not seem to cover this < <InnerBlocks template={[ ["core/paragraph", { placeholder: "Enter side content...", textColor: '#EF4A23' }] ]} />
**As of the end 2020** , I have found that the best way to find attributes related to a core block is to inspect it with the react developer tools. Under the components tab, search for `[BLOCK_NAME]Edit` to find the editing component, where `[BLOCK_NAME]` is something like "Paragraph", "Heading" or "Button". Then on the right side in the inspector you can see the related attributes. **To answer the original question** , at the current moment, the attribute is `textColor`. const TEMPLATE = [ [ 'core/paragraph', { textColor: '[YOUR-COLOR-SLUG]', }, ] ] In my case entering an hexadecimal value doesn't seem to work. But this might be because I have disabled the custom color selector globally.
stackexchange-wordpress
{ "answer_score": 5, "question_score": 6, "tags": "block editor" }
Wordpress API standard compliance and specification for external database HOW TO CONNECT WORDPRESS WITH EXTERNAL DB SERVER VIA API?
WordPress has the HTTP API that you could perhaps use to send POST (`wp_remote_post`) or GET (`wp_remote_get`) requests to an API, < But you could also use cURL to send the requests, I think. If the API is developed by you, then it's up to you to decide what kind of arguments the API accepts/expects and what kind of authentication it requires. If it's some 3rd party API, then you need to consult the API documentation to see what is needed to get a response from it and in which form you'll get the response - e.g. is it a JSON response. Or if you can skip the API and connect directly to the database, then you could perhaps use `$wpdb` to do it as described here, Using wpdb to connect to a separate database
stackexchange-wordpress
{ "answer_score": 0, "question_score": -1, "tags": "database, rest api, api" }
Extra url paths as variable I have this WordPress pretty permalinks structure: < (where house define post_type) I want this one url: < (that works like < and parse 2 as "nights" variable and 3 like "people" variable). Is this possible? I have search but not found any similar question. Thanks in advance.
The correct way to register the rewrite rule and rewrite tag for your case is: function custom_rewrite_rules() { add_rewrite_tag('%nights%', '([^&]+)'); add_rewrite_tag('%people%', '([^&]+)'); add_rewrite_rule('house/(.+)/(.+)/(.+)/?$', 'index.php?house=$matches[1]&nights=$matches[2]&people=$matches[3]', 'top'); } add_action('init', 'custom_rewrite_tag', 10, 0); The code has been tested and works correctly.
stackexchange-wordpress
{ "answer_score": 0, "question_score": 0, "tags": "permalinks, url rewriting, urls" }
How can I get the custom post title? I need to get the title from my custom post but its showing from my default post. here is my code. please help.![enter image description here](
Simply, `echo get_the_title( $slide );` the_title(), or get_the_title() will not work here.
stackexchange-wordpress
{ "answer_score": 0, "question_score": 0, "tags": "php, title" }
Get permalink to latest post in category I need to get the permalink to the latest post in just one category. That link then needs to be placed into a button. The button is rendered within a function in a custom front-page.php template. I have this so far but it is not working with various permutations and no errors are showing up: $latest_post = get_post( array( 'cat' => 3, 'posts_per_page' => 1) ); if( $latest_post ) { echo '<a href= "' . get_permalink( $latest_post->ID ) . '">Learn More Now</a>'; } Can anyone help show me where I've gone wrong?
The function you are using here, `get_post()` does not accept query arguments. So you have to use `get_posts()`. Try this: $latest_post = get_posts( array( 'cat' => 3, 'posts_per_page' => 1) ); if( !empty( $latest_post ) ) { echo '<a href= "' . get_permalink( $latest_post[0] ) . '">Learn More Now</a>'; }
stackexchange-wordpress
{ "answer_score": 0, "question_score": 0, "tags": "categories" }
In wp_list_comments(), what is a short_ping? I've been looking at the documentation for `wp_list_comments()`. One of the options is 'short_ping' which is documented thus: > ( boolean ) Whether you want to use a short ping. What on earth is a "short ping" and why would I want one?
This option is used to output a pingback comment. It's passed to the `Walker_Comment` class, and if it's set to true, it will output something similar to this: <li> <div class="comment-body"> Pingback: <a href="author-url-here" rel="external nofollow" class="url">Author Name</a> </div> The author URL is the field that users enter when filling out the comment form. Note that the closing `</li>` is missing intentionally.
stackexchange-wordpress
{ "answer_score": 3, "question_score": 1, "tags": "comments" }
Can I use wp_oembed_get to detect a valid embeddable link or is there a better way to do so? I am looking for an efficient way to detect if user input is a valid embed link (and of what type). I know that one can cause WordPress to run its embed code with arbitrary input. For example, like this: $embed_code = wp_oembed_get($some_string); if($embed_code!=FALSE){ // do something clever } Assuming that there is at least some link, it will return a fully marked up link failing all else. The behaviour I am after, however, is to be able to feed it some user input (after appropriate sanitation) and get back either a fully marked-up embed or a FALSE but not a hyperlink if the content is a URL that it does not recognise. The purpose is to detect if the given input text is a valid embeddable URL. Can (or should) I use `wp_oembed_get` to detect a valid embeddable link or is there a better way to do so?
The regex patterns for matching embeddable URLs are stored in `WP_oEmbed`, which has the method `get_provider()` for checking if a given URL is an embeddable URL for a supported provider. Just set the `discover` argument to false if you don't want to actually send a request to the URL to test it, and just want to match the regex: $url = ' $oembed = new WP_oEmbed(); $provider = $oembed->get_provider( $url, [ 'discover' => false ] ); if ( false !== $provider ) { // Is embeddable. }
stackexchange-wordpress
{ "answer_score": 3, "question_score": 1, "tags": "embed, oembed" }
When creating a blog post through the WYSIWYG editor, text is not being wrapped in <p> tags correctly when starting with a link When creating a new blog post, and the first item is a link follewed by text like this: `<a>Some link</a> some text` When this is rendered into HTML The tags get placed at the end of the text like this: `<a>Some link</a> some text<p></p>` If there is any text before the link at the beginning then tags are wrapped correctly. I have gone into wp-includes/formatting.php and am not able to find source of this problem... Any insight or suggestions would be greatly appreciated. Thanks.
May this will helpful for you 1) There will be no p tag will wrap while starting with anchor tag. The editor will takes a each paragraph in a paragraph tag.(Whether it may any tag, the editor will all the html content inside of p tag) 2) If you are using wordpress default post editor means just print it by using the_content() or get_the_content($post_id) . 3) If you are using Custom Field (ACF) means use apply_filters(). <?php echo apply_filters('the_content', 'your_field_name');?>
stackexchange-wordpress
{ "answer_score": 1, "question_score": 0, "tags": "wysiwyg" }
Logout redirects to a broken page(home URL is omitted) I'm using the latest version of WP. I have a problem, where clicking the logout button from the admin panel redirects to a completely broken link: > < As you can see, the domain is completely omitted from the link(in my case it's wp.localhost) I will mention that this local WP site was "cloned" from a remote server, but i made sure to change the "siteurl" and "home" fields in the wp_options table, **and everything else works just fine** Can somebody tell me, where the problem might be? Is there any other configuration field, that might be relevant to this?
Found the answer. It is a bug in WordPress v5.2.3 affecting WordPress in Windows environments. Caused by backslashes in Windows paths that aren't stripped correctly Details here: < I have tried the patch suggested and can confirm it solves the problem. replace: $location = '/' . ltrim( $path . '/', '/' ) . $location; with $location = '/' . ltrim( $path . '/', '/\\' ) . $location; in /wp-includes/pluggable.php, line 1404 It says it will be fixed in version 5.2.4
stackexchange-wordpress
{ "answer_score": 2, "question_score": 2, "tags": "options, logout, home url" }
How do I use jQuery to add the TinyMCE WYSIWYG editor to a textarea? Using jQuery (as part of a theme or plugin) how can I add the WYSIWYG (TinyMCE) rich text editor to a `<textarea>`? Specifically, I want to activate it upon certain conditions being met (changes in the form etc.). I have a timer event that checks the text size periodically for a number of reasons, this will be the function that activates the editor. What do I need to do to make the TinyMCE available on a front end and attach/activate it as required? (looks like the user is writing a lot of text, activate TinyMCE). I assume there is something I need to enqueue but, beyond that, I'm just guessing. My question is related to this one but differs in that I want to do this with jQuery. Also related, this one, but that's only a partial answer (I still need to know what to hook). I need to set it up and then activate with jQuery.
I would just use the WordPress JavaScript API for TinyMCE -- `wp.editor`. The steps in brief: 1. PHP: Enqueue the editor scripts (and styles) via `wp_enqueue_editor()`. 2. JS: Call `wp.editor.initialize()` from your script. And do take note of this: (the "this function" refers to `wp.editor.initialize`) > If this function does nothing, please make sure that `wp.editor.getDefaultSettings` is a function. Which means, if it's not a function, then while there are no errors thrown in the browser/console, the `textarea` will not be converted to a TinyMCE editor.
stackexchange-wordpress
{ "answer_score": 1, "question_score": 0, "tags": "jquery, tinymce" }
Can I hook error_log(...)? Is there a hook for error_log(...) ? On my development environment I would like to var_dump the results instead of having to check the log file each time.
Try using standard function from PHP set_error_handler()
stackexchange-wordpress
{ "answer_score": 1, "question_score": 1, "tags": "logging" }
When creating a post how do you select the format? When creating a post programmatically (with `wp_insert_post();`), how do you select the format?
As post_format is a custom taxonomy and the different formats terms, you should be able to use the `tax_input` parameter in the new post args array to set the format. Something along these lines, $new_post_args = array(); // e.g. $format_slug = 'gallery'; $valid_formats = get_post_format_slugs(); if ( 'standard' !== $format_slug && in_array( $format_slug, $valid_formats ) ) { $new_post_args['tax_input']['post_format'] = 'post-format-' . $format_slug; } wp_insert_post( $new_post_args );
stackexchange-wordpress
{ "answer_score": 1, "question_score": 0, "tags": "posts, wp insert post" }
Headless Wordpress + Vue.js on the same server I have found many articles about headless wordpress and vue.js using data via WP REST API. In these articles they deploy the app on separate servers. Backend is on different server than frontend. I'm trying to find out how to deploy the app on one server. Until now I come up with one solution: On the server create subfolder ( subdomain ) for CMS and on public upload the Vue frontend and pull the data from subdomain via WP REST API endpoint. Is it possible to connect Wordpress and Vue without creating subdomain? I would like to upload the vue app right in the folder where is Wordpress. I think I can't put it in the theme folder of the wordpress and keep it separate at the same time. Any solutions?
Yes, it is possible to connect WordPress and Vue without a subdomain. As you're pulling data via the WP REST API it doesn't matter where WP is - same or different server, subdomain or subfolder - as long as you know its url. You could have your Vue related files (e.g. index.html, app.css, and app.js) for example in /public_html and WP installed in /public_html/wp folder. You could then access WP from youdomain.com/wp and your app would be in yourdomain.com. Mixing WP files and your Vue app files probably isn't a good idea as WP needs its index.php to function properly. But you could create a theme with just a index.php file in it, which would load your app scripts and the app root (i.e. `<div id="app"></div>`) element.
stackexchange-wordpress
{ "answer_score": 1, "question_score": 0, "tags": "theme development" }
What's the difference between home_url() and get_home_url() from a developmental point of view? Both functions return the website url. And, as home_url() needs sanitization (for example `<?php echo esc_url( home_url( '/' ) ); ?>)`, why it is this snippet of code, instead of `<?php echo get_ home_url( '/' ); ?>`, that we found in Wordpress Codex and Wordpress Template Twenty Nineteen ?
There isn't much difference but they are **not** the same. ### get_home_url `get_home_url()` takes null or a blog id as the first parameter. As per documentation here. > get_home_url( int $blog_id = null, string $path = '', string|null $scheme = null ) If you are dealing with multiple homes (as in, say a multi-site set up) this might be useful. ## home_url `home_url()`, on the other hand, is less fussed about per blog settings and just wants the home URL. As per documentation here. > home_url( string $path = '', string|null $scheme = null ) It is the equivalent of calling `get_home_url( null, $path, $scheme );`. Most of the time, this is the function you want.
stackexchange-wordpress
{ "answer_score": 2, "question_score": 4, "tags": "home url" }
Using a `Template Parts` folder instead of an `Includes` folder in a Custom Wordpress Theme When I've built static sites in the past I've had an includes folder and used php if I've needed to repeat components / HTML over different pages. I've noticed in Wordpress that this functionality is undertaken with a `template-parts` folder which seems to do the same thing. I'm about to start building a custom theme for the 1st time and my question is, is there a reason why I should use `template-parts` instead of an `includes` folder, and if I use an `includes` folder will there be any negatives to this? Many thanks
It doesn't matter. It just has to do with standard naming in WordPress because you typically call your "parts" with `get_template_part();`. `get_template_part();` checks if the file is in the child theme first, then uses the one from the parent theme if it doesn't. It provides a way for you to override template files from the child theme.
stackexchange-wordpress
{ "answer_score": 1, "question_score": 1, "tags": "php, theme development, directory" }
display custom plugin view on front end inside template body EDIT May be my question is not well formed i need to use the url < to display a house plugin view somewhere in plugin directory function getHouses(){ include plugin_dir_path(__FILE__) . 'public/publicHouse.php'; } the result i'm getting is on the picture below ![enter image description here]( I'm expecting the view with the whole template and houses view inside body template area any help is appreciated
@Frank P. Walentynowicz i dit it with fake post and it worked. on this link wordpress fake post
stackexchange-wordpress
{ "answer_score": 0, "question_score": 0, "tags": "php" }
Alternate email sending service - eg: AWS SES I noticed my shared hosting service have a delayed email sending service. This is not good to serve my WordPress site. Is there a solution for this (eg. plugin) that can plug into another email service such as AWS SES? If so how to do so?
I've used this plugin on websites to connect to AWS SES or SendGrid: < You can see more SMTP plugins here: <
stackexchange-wordpress
{ "answer_score": 1, "question_score": 0, "tags": "plugins, email, amazon, web services" }
Is there a way to test if a URL is part of the current blog? In a scenario where, say, your plugin or theme has been given a URL. You want to know, is this URL a URL from this very blog? How would you test if it is?
One option could be to use `url_to_postid( $url )`, which returns a " _ID of the post or page that resides at the given URL, or 0 on failure._ ", < But this doesn't work with archives, I think. To find out if the url is for an archive, you'd probably need to `explode()` the path and then do some kind of `get_term_by()` with the parts. Perhaps a little less strict way would be to compare the url's host to your domain, if ( false !== strpos( get_home_url(), parse_url( $some_url, PHP_URL_HOST ) ) ) { // do something } or if ( parse_url( $some_url, PHP_URL_HOST ) === parse_url( get_home_url(), PHP_URL_HOST ) ) { // do something } But doing it this way, you wouldn't know, if the path was correct or not.
stackexchange-wordpress
{ "answer_score": 1, "question_score": 0, "tags": "urls" }
Hide price and add to cart button on product page only I’m using Datafeedr to show price comparison sets on a product page. The price comparison table opens up dynamically once the page is loaded. But because I want people to follow the link to the cheapest store that offers that product I really have no use for each imported product to show it’s own price. That price could be higher than the prices that are shown in the comparison table and the link of the button would then send the visitor to the wrong store. I have a plugin that turns of the prices and add to cart buttons, but it also turns of the prices on the category pages. And I do want the prices to show there because on the category pages people can filter the prices or set a price range. Can someone tell me with which snippets I can leave the prices in the category pages, but hide them on the single product pages and also how to hide the add to cart button? Thanks very much!
This will remove price and add to cart button on the product page Only // Remove Price from the product page remove_action( 'woocommerce_single_product_summary', 'woocommerce_template_single_price', 10 ); // Remove Add to cart form from the product page remove_action( 'woocommerce_single_product_summary', 'woocommerce_template_single_add_to_cart', 30 );
stackexchange-wordpress
{ "answer_score": 1, "question_score": 0, "tags": "woocommerce offtopic" }
Woocommerce - Shipping tax class based on cart items not using the highest tax available We have the "Shipping tax class" option on "Shipping tax class based on cart items". When I add a free tax product to the shopping cart and a 21% tax product to the shopping cart together, the total tax for the shipment is 0. That is incorrect because it should be 21%. When I add only one product to the shopping cart it uses the correct tax, but not with 2 products of differtent taxe rates.
I have found the answer by override the shipping tax filter // 0% and 21% tax producdts added combined to the cart needs to have 21% shipping tax add_filter('woocommerce_shipping_packages', 'override_woocommerce_shipping_packages'); function override_woocommerce_shipping_packages($packages) { $shipment_needs_tax = false; foreach ($packages[0]['contents'] as $cartitem) { if (!empty($cartitem['data']->tax_class)) $shipment_needs_tax = true; } if ($shipment_needs_tax && empty($packages[0]['rates']['flat_rate:3']->get_taxes())) { $shipcost = $packages[0]['rates']['flat_rate:3']->get_cost(); $shiptax = $shipcost * 0.21; if ($shiptax > 0) $packages[0]['rates']['flat_rate:3']->set_taxes([4 => $shiptax]); } return $packages; }
stackexchange-wordpress
{ "answer_score": 0, "question_score": -1, "tags": "php, functions, woocommerce offtopic, tax query" }
Query posts with "non set" meta value I'd like to make a query of custom posts based on a custom field, say `instrument`. I need to be able to query only those posts for which the custom field has not been set (i.e. for which the meta value does not exist). Is there a way to achieve this with `meta_query` ? Here's the code for the query : $args = array( 'post_type' => 'my_custom_post_type', 'nopaging' => true ); $args['meta_query'] = array( array( 'key' => 'instrument', // when value is not even set. ) ); } $the_query = new WP_Query( $args );
As documented, you can set the `compare` property of the meta query to `NOT EXISTS`: $args['meta_query'] = array( array( 'key' => 'instrument', 'compare' => 'NOT EXISTS', ), );
stackexchange-wordpress
{ "answer_score": 2, "question_score": 0, "tags": "wp query, meta query" }
Connect to database in the header of my WordPress website I have created a table in my WordPress database. Now, WordPress gets all its data about different posts and pages from the database. This means that WordPress always connects to database automatically without theme developers writing any code. I want to get information from a table I added to the database inside the `header.php` file of my theme. My question is do I need to create a WordPress database connection by loading all the files like require_once(__DIR__."/../wp-load.php"); require_once(__DIR__."/../wp-config.php"); $connection = new mysqli(DB_HOST, DB_USER, DB_PASSWORD, DB_NAME); Or I can use the existing database connection. If I can use the existing database connection, how do I do that? Thanks.
You can (and should) use the existing database connection by accessing `global $wpdb`. The simplest way to use it is with the `get_results()` method: global $wpdb; $results = $wpdb->get_results( 'SELECT * FROM my_table' ); There's other methods available, and things you need to consider like preparing queries and using the correct table prefix (if your table has one). An overview for all this is available in the Codex, and you'll find many helpful guides if you search Google for "wpdb".
stackexchange-wordpress
{ "answer_score": 1, "question_score": 0, "tags": "database" }
Adding product SKU before cart item name in WooCommerce I have this snippet that adds product SKU after cart item name in cart, mini-cart and checkout: function show_sku_in_cart_items( $item_name, $cart_item, $cart_item_key ) { // The WC_Product object $product = $cart_item['data']; // Get the SKU $sku = $product->get_sku(); // When sku doesn't exist if ( empty( $sku ) ) return $item_name; // Add the sku if ( is_cart() ) { $item_name .= '<br><small class="product-sku">' . '<span class="sku-title">' . __( "SKU: ", "woocommerce") . '</span>' . $sku . '</small>'; } else { $item_name .= '<small class="product-sku">' . $sku . '</small>'; } return $item_name; } add_filter( 'woocommerce_cart_item_name', 'show_sku_in_cart_items', 99, 3 ); But I need to add this before cart item name.
You just need to change a bit your code this way, to get the SKU **before** the product name: function show_sku_in_cart_items( $item_name, $cart_item, $cart_item_key ) { // The WC_Product object $product = $cart_item['data']; // Get the SKU $sku = $product->get_sku(); // When SKU doesn't exist if ( empty( $sku ) ) return $item_name; // Add SKU before if ( is_cart() ) { $item_name = '<small class="product-sku">' . '<span class="sku-title">' . __( "SKU: ", "woocommerce") . '</span>' . $sku . '</small><br>' . $item_name; } else { $item_name = '<small class="product-sku">' . $sku . '</small>' . $item_name; } return $item_name; } add_filter( 'woocommerce_cart_item_name', 'show_sku_in_cart_items', 99, 3 );
stackexchange-wordpress
{ "answer_score": 2, "question_score": 1, "tags": "woocommerce offtopic" }
Merge two search functions for custom post type In addition to the site-wise search. I have a custom search for a certain post type and with different ordering than the global search. Here are the two function, which works. I wonder if those two can be merged into one, or simplified if possible? function _s_staff_search($template) { global $wp_query; if ($wp_query->is_search && 'staff' === get_query_var('post_type')) { $template = get_template_part('template-parts/staff-search'); } return $template; } add_filter('template_include', '_s_staff_search'); function _s_staff_query($query) { if ($query->is_search() && 'staff' === get_query_var('post_type')) { $query->query_vars['orderby'] = 'name'; $query->query_vars['order'] = 'ASC'; } } add_filter('parse_query', '_s_staff_query');
Your functions are already simple enough, and secondly, the functions do different things: * `_s_staff_query()` filters the posts query variables and the function has to run _before_ `WP_Query` queries the database. * `_s_staff_search()` filters the search results template and the function has to run _after_ `WP_Query` queries the database. So just keep them independent.
stackexchange-wordpress
{ "answer_score": 2, "question_score": 0, "tags": "wp query, functions" }
file_exists function does not work $filecs=get_stylesheet_directory_uri().'/css/lucilevi.css'; $filejs=get_stylesheet_directory_uri().'/js/lucilevi.js'; if (file_exists($filecs)) { echo "CS found"; } else{ echo "CS not found"; } if (file_exists($filejs)) { echo "JS found"; } else{ echo "JS not found"; } Although the path for directory is correct it returns false. Can Anyone explain why this happen? I am new to PHP and Wordpress. Thanks.
`file_exists()` lets you check if a file exists on the local server, by passing it a file _path_. It cannot be used to check for the existence of files via _URL_ , and you're passing it the result of `get_stylesheet_directory_uri()`, which returns the URL (http:// etc.) to the file, not the path. The proper way, these days, to get the _path_ to a theme file is to use `get_theme_file_path()`, like so: $filecs = get_theme_file_path( 'css/lucilevi.css' ); $filejs = get_theme_file_path( 'js/lucilevi.js' ); if ( file_exists( $filecs ) ) { // etc. } if ( file_exists( $filejs ) ) { // etc. } Just be aware that because `$filecs` and `$filejs` are file paths, you cannot pass them to `wp_enqueue_style()`, `wp_enqueue_script()`, you still need to pass URLs to those.
stackexchange-wordpress
{ "answer_score": 1, "question_score": 0, "tags": "php" }
Htaccess redirect after changing Language URL format After have changed the URL language format from to I'd like to redirect the former URL versions to the actual ones. I found this code snippet online and apparently it partially solves my problem. <IfModule mod_rewrite.c> RewriteEngine on RewriteCond %{QUERY_STRING} lang=en # exclude all requests starting with /wp-admin/ RewriteCond %{REQUEST_URI} !^/wp-admin/.*$ RewriteRule ^(.*) /en/$1? [L,R=301] </IfModule> However, it is designed for `lang=en` only! How could I also include `lang=ru` in it so that it will redirect both `lang=en` and `lang=ru`? Thank you in advance for any valuable hint!
In order to catch either `lang=en` or `lang=ru` you can change those directives like this: RewriteCond %{QUERY_STRING} lang=(en|ru) # exclude all requests starting with /wp-admin/ RewriteCond %{REQUEST_URI} !^/wp-admin/ RewriteRule (.*) /%1/$1? [L,R=302] The `(en|ru)` part matches either `en` or `ru` and the surrounding parentheses make this a _capturing group_ that can be referenced later. The `%1` (note the `%`, not `$`) in the `RewriteRule` _substitution_ is a backreference to the captured group mentioned above. So, `%1` holds either `en` or `ru`. The trailing `.*$` on the end of `!^/wp-admin/.*$` is superfluous. As is the `^` prefix on the `RewriteRule` _pattern_ `(.*)` \- since regex is greedy by default. Test first with a 302 (temporary) redirect and only change to 301 (permanent) when you are sure this is working OK - to avoid caching issues.
stackexchange-wordpress
{ "answer_score": 1, "question_score": 1, "tags": "htaccess" }
auto link word link in content i use this code for auto link word in content <?php function link_words($content){ $words=array( 'test1', 'test2', 'test3' ); $links=array( '<a href="/tag/test1/" rel="nofollow">test1</a>', '<a href="/tag/test2/" rel="nofollow">test2</a>', '<a href="/tag/test3/" rel="nofollow">test3</a>' ); $content = str_replace($words,$links,$content);return $content;} add_filter('the_content','link_words'); add_filter('the_excerpt','link_words'); ?> but upper code have one problem, so changed and linked any word (images alt , ...) i want only word between `<p></p>` i want finally link any word in content to tags and categories
If I understand correctly ... first of all you need to match everything inside paragraphs using regex. $content = "<p>some text which includes test1 and test2 etc</p>"; preg_match_all("/<\s*p[^>]*>([^<]*)<\s*\/\s*p\s*>/", $content); then you can use your code.
stackexchange-wordpress
{ "answer_score": 0, "question_score": 0, "tags": "the content" }
Create and Update 2 CPT sequentially Is it possible to create + update a CPT after a post have been created sequentially in the same flow? For example: First: I do a wp_insert_post($my_first_cpt) (with some data, and it's executed on save_post hook) Second: wp_update_post($my_second_cpt) (with DATA from $my_first_cpt, for example a random seed) and show be executed inmediately after So essentially $my_first_cpt has to be created and stored and inmediately afterwards, something has to fire to get data from $my_first_post and update $my_second_post Is this possible? I've tried to put one after another and it doesn't simply work.
I've found a solution, which I'm not liking much, but it works Essentially what I do is create two hooks to save_post (in this case this is the action that launches this script) with different priorities for example 10 and 20 In the priority 10 I put the wp_insert_post And in the priority 20 I put the wp_update_post It works, but is doesn't seem to be the best solution...
stackexchange-wordpress
{ "answer_score": 0, "question_score": 0, "tags": "custom post types" }
Can site visitors view functions.php file? I'm pretty sure the answer is "No, they can't see functions.php or any theme php files" but I can't find an answer anywhere.
It's always difficult to prove that something isn't there, like the famous teapot circling the earth. So you'll have to trust me that the WordPress source code does not have any functions that might display its own `php` files. That said, it would be easy to write such code. So, if you install plugins of unknown origin or do otherwise ill advised things to your site, you could still expose `functions.php`. Not strictly speaking a WordPress issue would be your server's security. If you set file permissions wrongly (in `.htaccess` for instance), you could make all your files visible from the outside.
stackexchange-wordpress
{ "answer_score": 0, "question_score": 0, "tags": "functions" }
how to use custom page template in a page? I have a custom page template, and I want to use this in my page. I have created a new page and in template choose custom page template name. It's working, but I have added 4 blocks in my page, and this not working. I want to use the custom page template with wordpress page text. I want to use both custom page template and text blocks as well.
Your template should include the_content so that content from your editor is displayed in your page. <?php the_content(); ?> It would be better if you posted the php code of the page template you created, to find the exact issue.
stackexchange-wordpress
{ "answer_score": 1, "question_score": 1, "tags": "templates, page template" }
Meta query compare for ID's greater than specific ID I just want to grab all posts that have a greater value than a supplied post ID 'meta_query' => array( 'relation' => 'AND', array( 'key' => 'rid', 'value' => $rid, 'compare' => '=', 'type' => 'numeric', ), array( 'key' => ID, 'value' => $last_id, 'compare' => '>', 'type' => 'numeric' ), ), So if $last_id is "350", I want to grab all posts with a higher ID than 350
You can use prepare: global $wpdb; $post_ids = []; $last_id = 350; $query = $wpdb->prepare( " SELECT ID FROM $wpdb->posts WHERE ID > %d ", $last_id ); $results = $wpdb->get_results( $query ); // it will convert the IDs from row objects to an array of IDs foreach ( $results as $row ) { array_push( $post_ids, $row->ID ); } //now you can set up your query $custom_args = array( 'posts_per_page' => 100, 'post__in' => $post_ids ); $custom_query = new WP_Query( $custom_args ); if( $custom_query->have_posts() ) : while( $custom_query->have_posts() ) : $custom_query->the_post(); echo get_the_title() . '<br>'; endwhile; endif; Reference **Note:** You can change condition as per your requirement `>, >=, <, <=` etc.
stackexchange-wordpress
{ "answer_score": 1, "question_score": 0, "tags": "wp query, loop, meta query" }
Page template that redirects user based on role I'm trying to come up with a wordpress page template (acting as a landing page) that redirects a user to another page based on their role. ex. user with role editor goes to landing page and is redirected to "/editors-page/" user with role subscriber goes to landing page and is redirected to "/subscribers-page/" I've come across so many plugins and custom functions that talk about redirecting at login but I'm using multisite and there are some complications using any of those examples so I've landed on the above solution. Any help would be wonderful! Thanks so much!
You can use `current_user_can()` to check the user roles. < To check if the user is editor or administrator: <?php if( current_user_can('editor') || current_user_can('administrator') ) { ?> // Stuff here for administrators or editors <?php } ?> Then to redirect you can use this: header('Location: '.$newURL);
stackexchange-wordpress
{ "answer_score": 0, "question_score": 1, "tags": "redirect, user roles" }
Link From Single Post To Taxonomy Term Archive Page Need to add a link on all single pages for custom post type taxonomy terms which links back to the taxonomy term archive the single page belongs to. Using this code but it adds links for all tax terms. I only need the one the single page is assigned to. $terms = get_terms( array( 'taxonomy' => 'portfolio', ) ); if ( ! is_wp_error( $terms ) && ! empty( $terms ) ) { foreach ( $terms as $term ) { echo '<a href="' . get_term_link( $term->slug, 'portfolio' ) . '">' . $term->name . '</a>'; } } I added this code in the single-portfolio.php file
Seems like a good use for `get_the_term_list()` <
stackexchange-wordpress
{ "answer_score": 1, "question_score": 0, "tags": "custom post types, custom taxonomy" }
how to display specific Category if post have more one Category? how to display specific Category if post have more one Category? in single.php, i want to get specific Category for post i need a code that cheks all post Category and display just the one in specific main Category. like that $category = get_the_category(); if category( in_parent('11') ){ $parent = $category[1]->category_parent; } for my site maktaba
Confusingly, `get_the_category()` returns an array of categories, so you're going to need to loop through them. It sounds like you want whichever category is assigned to the current post, and is also a sub-category of category id 11. If that's the case, use <?php // Get all the categories assigned to this post $categories = get_the_category(); // Loop through the array that was returned foreach($categories as $category) { // If this category is a sub-category of category 11 if($category->parent == 11) { // Set the $parent to it $parent = $category; // And exit the foreach loop break; } } ?>
stackexchange-wordpress
{ "answer_score": 0, "question_score": 0, "tags": "categories" }
How to append classname to body tag if guest user By default when a user is logged in, a 'logged-in' classname is appended to the body tag. I need to append something like 'guest-user' to the body to output different styling based on whether or not the user is logged in. How can I achieve this? Something maybe I could put in my child theme's functions.php file? Thanks.
Yes, there's the body_class filter. You could use e.g. function body_class_guest_user( $classes, $class ) { if ( ! is_user_logged_in() ) { $classes[] = 'guest-user'; } return $classes; } add_filter( 'body_class', 'body_class_guest_user', 10, 2 ); However you could equally well just use the :not() selector, e.g. `body:not(.logged-in)` (browser support), or absence of logged-in i.e. set up the guest-user styling as default but then override it if `.logged-in`.
stackexchange-wordpress
{ "answer_score": 1, "question_score": 0, "tags": "functions, customization" }
Headless WordPress – Issue with plugin path Working on my first decoupled site. Backend is handled by WordPress and lives on the subdomain `admin.mydomain.com` and the frontend lives at `mydomain.com`. The first issue I saw with the headless approach, was that all permalinks referred to `admin.mydomain.com`. I wanted to change that so that the backend referenced to my frontend. So I changed my config from: `WP_HOME=' `WP_SITEURL=' to: `WP_HOME=' `WP_SITEURL=' which sorted my issue with the permalinks, but now I'm getting console errors on the WP dashboard because the plugins can't find the resources they need, for example ACF: index.php:63 GET net::ERR_NAME_NOT_RESOLVED What would be the proper course of action to fix this?
My quick and dirty fix looks like this (please note that I use Roots Bedrock, so it differs from a vanilla WP install). 1. In .env add this line `WP_HOME_ADMIN=' 2. In application.php add this line, preferable just after where `WP_HOME` is defined: `Config::define('WP_HOME_ADMIN', env('WP_HOME_ADMIN'));` 3. Somewhere after where `CONTENT_DIR` is defined, add this line: `Config::define('WP_PLUGIN_URL', Config::get('WP_HOME_ADMIN') . Config::get('CONTENT_DIR') .'/plugins');`
stackexchange-wordpress
{ "answer_score": 2, "question_score": 1, "tags": "api, site url, home url, headless" }
Does having category name in permalinks affect SEO when having a post in multiple categories? If I change the permalink structure to the following in the Permalinks settings page in WordPress: `www.example.com/%category%/%postname%/` Then I create a post with the slug `my-post` and add two categories for that post `category1` and `category2`, will Google see this as duplicate content because if you go to both these links: `www.example.com/category1/my-post/` `www.example.com/category2/my-post/` They will go to the same post but the URL does not change, isn't this classed as duplicate content? Will Google and other search engines penalise a site that uses this practice? What is the recommend approach to this problem?
It should not affect it because Wordpress redirects links to post leaving you with only one canonical and working one. Post would be visible in both categories but will have only one correct permalink.
stackexchange-wordpress
{ "answer_score": 0, "question_score": 0, "tags": "posts, categories, permalinks, urls" }
Changing Date Format on Custom Meta Data w/shortcode call I am currently pulling a date from a users meta and making it so I can input a shortcode and it will show that date in certain places. I have the following code written and it works great! function delivery_date( $atts ) { global $current_user, $user_login; get_currentuserinfo(); add_filter('widget_text', 'do_shortcode'); if ($user_login) return $current_user->delivery_date ; } add_shortcode( 'delivery_date', 'delivery_date' ); Now, my problem is that the date is showing up at Y-m-d (2019-09-25) but I want it to show up as d-m-Y (09-25-2019). What is the best way to do this? What do I need to add to my code and where? All help is much appreciated! Thank you!
Try with change line to `date('d-m-Y',strtotime($current_user->delivery_date)) ;` function delivery_date( $atts ) { global $current_user, $user_login; get_currentuserinfo(); add_filter('widget_text', 'do_shortcode'); if ($user_login) return date('d-m-Y',strtotime($current_user->delivery_date)) ; } add_shortcode( 'delivery_date', 'delivery_date' ); echo do_shortcode('[delivery_date]');
stackexchange-wordpress
{ "answer_score": 0, "question_score": 0, "tags": "php, shortcode, date, formatting" }
Adding additional html to the end of the root level in a custom nav walker I have a custom nav walker, which essentially just add's new classes to the menu, however, my menu also contains some hard coded elements at the end (Contact button & Search Icon). Where/How to I add this custom `<li>`'s in the nav walker to ensure that these get added in the root UL as the last items, only once?
Hope this code will helpful for you, add the items_wrap in wp_nav_menu to merge li's <?php wp_nav_menu( array( 'theme_location' => 'primary', 'container' => '', 'menu_id' => '', 'menu_class'=> '', 'items_wrap' => '<ul id="%1$s" class="%2$s">%3$s<li><a href=" href="javascript:void(0);">Search</a></li></ul>' ) ); ?>
stackexchange-wordpress
{ "answer_score": 0, "question_score": 0, "tags": "menus, navigation, walker" }
How can style text like this in wordpress I want to know how I can style the backgourund of text like this as shown in imgae I snipt it from here ![enter image description here](
Add span tag to text you want background for and apply css- background-color and font-style: italic on span <p><span class="red">VDD</span> GND is used for driving the internal logic circuitry</p> Then add the following into your WordPress CSS (your theme will have a css file, but may have a place to add custom styles in the Dashboard). .red { background-color: red; padding: 0px 5px; color: #fff; border-radius: 3px; display: inline-block; -webkit-transform: skew(-10deg); -ms-transform: skew(-10deg); transform: skew(-10deg); -moz-transform: skew(-10deg); -o-transform: skew(-10deg); }
stackexchange-wordpress
{ "answer_score": 1, "question_score": 0, "tags": "customization, text" }
Hook to change HTTP response headers I want to write a simple Wordpress plugin. The plugin will: 1. Read (if set) a cookie from the visitor 2. Send a cookie (if not set) to the visitor 3. Depending on the cookie value I will redirect the user to a new pages I found some documentation for getting/setting cookies through WP, and I'm guessing I can just issue a redirect from PHP. So I downloaded the WordPress Boilerplate (WPBP) code and so far so good. But I'm stuck at: 1. Which WP callback should I hook into for my code? (init ?) I found the plugin documentation but I'm struggling to understand where this type of code should hook into. 2. Should I put any of my code into the main/global portion of the WPBP file? Or only in the called back function. 3. This plugin will run on a WP multisite installation. Does that mean my plugin code would run on every site? If so, how could I restrict my plugin code to run on only a particular site? (PHP check for a URI?)
Your questions about how you should structure your plugin are somewhat too broad, but here is a specific answer to the title question. To change headers before they’re sent, use the `wp_headers` filter. function tsg_filter_headers( $headers ) { // For debug. This will break your page but you will see which headers are sent // print_r( $headers ); // It’s a good idea to leave the admin alone if ( !is_admin() ) { // Add or redefine 'Content-Location' header $headers['Content-Location'] = '/my-receipts/42'; } return $headers; } add_filter( 'wp_headers', 'tsg_filter_headers' ); See the WordPress doc here.
stackexchange-wordpress
{ "answer_score": 1, "question_score": 0, "tags": "headers" }
Apostrophes replaced by &#39; I use a plugin for automatic posting of articles on social networks, and when I send an article on Facebook or Twitter from my website, the apostrophes of my articles are replaced by this: ' It is possible that the problem comes from the theme, but I am not sure. I tried to do a "search and replace" to replace this code with an apostrophe using a "regex" but it does not work at all
Your problem might be coming from the font of the theme. Try using a different font on your site.
stackexchange-wordpress
{ "answer_score": 0, "question_score": -1, "tags": "plugins, theme development, translation, regex" }
Enable Custom Fields For Custom Post Type When CPT Created Using Plugin My CPT is created using a plugin so i cannot edit the supports parameter to add support for custom fields. I tried using this code however it doesn't work either add_action('init', 'custom_child_init'); function custom_child_init() { add_theme_support( 'custom-fields' ); } How do i enable the custom field meta box on the Edit Page screen for single custom post types?
Try with this. just change `CPT` with your post type. function wpcodex_add_excerpt_support_for_cpt() { add_post_type_support( 'CPT', 'custom-fields' ); } add_action( 'init', 'wpcodex_add_excerpt_support_for_cpt' );
stackexchange-wordpress
{ "answer_score": 2, "question_score": 0, "tags": "custom post types, custom field" }
How to remove "Category : ..." I am using theme Twenty Sixteen. I created a menu using categories, and when I click on one and end up on a category page that has a "Category : ..." title. I would like to remove that title so that only posts are displayed. I found this similar post : Remove "Category Archives: title" at the top of a category page However, the theme files are not the same and I can't find a "category.php" file. Does anyone know where to find the line responsible for displaying that category title ? I would greatly appreciate your help, thank you :)
That title is coming from `archive.php` file of TwentySixteen theme. You can find a `<header>` code section in that file. What you can do, simply copy the `archive.php` file as `category.php` and then remove the following code section from `category.php` file: <header class="page-header"> <?php the_archive_title( '<h1 class="page-title">', '</h1>' ); the_archive_description( '<div class="taxonomy-description">', '</div>' ); ?> </header><!-- .page-header --> In case you want to show only Category name as page title, then instead of removing the above code from `category.php` file, just replace the `the_archive_title` method with: printf('<h1 class="page-title">%1$s</h1>', single_cat_title('', false));
stackexchange-wordpress
{ "answer_score": 1, "question_score": 1, "tags": "categories, title, theme twenty sixteen" }
Is it possible to take a new visitor to the site to a disclaimer page and then return them to their previous page? I am new to WordPress and I am looking to add a disclaimer page where they either "Agree" to some terms/conditions or "Do Not Aggree". When a visitor to the site enters, they are taken to the page where they then either Agree or do not agree and then they are returned to their previous page. Is this possible and if so where do I start? Thanks!
If you are new to WordPress I assume you do not have coding experience to be able to code a popup using Javascript on your own. For that reason I recommend using a popup plugin such as the one called WP Terms. There are many plugins that can help you do that. Otherwise you can set your homepage as a regular page, add two buttons on it, then each button redirect to your content.
stackexchange-wordpress
{ "answer_score": 0, "question_score": 0, "tags": "redirect, terms" }
Turning Existing Eccommerce Site into Multi-SIte I have an existing multi-site that is a pretty in-depth e-commerce (woo) site with lots of features (free-shipping, discounts, memberships.) I need to create a sub-brand for an existing product, leveraging the existing theme and functionality. I figured the best way to turn the existing site into a multi-site. Am guessing some plugins I will have to buy different licenses etc. But mainly am afraid that all the functionality will break on the existing site, is this true? has anyone had experience with something like this?
I develop locally in a non-multi-site environment, then push to a multi-site (not the users or user_meta tables). Most plugins will work, but some expressly do not, so you should check with each first. This workflow was used on a WooCommerce site with no issues. Get comfortable with the table structure differences between standard and multi-site and make backups before proceeding, too.
stackexchange-wordpress
{ "answer_score": 1, "question_score": -1, "tags": "plugins, woocommerce offtopic, multisite, e commerce" }
How to remove padding from left&right side Im trying to remove the padding from left&right side by following custom css but doenst work #main.site-main,.container, .site-content{ margin: 0; padding: 0em; } Please advise how to solve this. The website is www.taro0329.com Thank you
Instead of setting up margin/padding. Try setting up max-width of `full-container` a `<div>` next to `site-main`: body.responsive.layout-full #page-wrapper .full-container { max-width: 95%; margin-left: auto; margin-right: auto; } You can change `max-width` to your desired percentage value.
stackexchange-wordpress
{ "answer_score": 0, "question_score": 0, "tags": "css" }
Yoast SEO settings unavailable in an archive page from wordpress plugin My Wordpress site has "Seriously Simple Podcasting" plugin installed to serve the podcast feature. This plugin comes with a podcast archive page(click to open) on my site. The page shows correctly for users, but lacking 2 important SEO functions: 1. Yoast plugin is unavailable/invisible, i.e. I cannot set `search keyword`, `meta description` etc for this archive page. 2. I cannot change the H1 title from `Podcast Archive` to whatever I'd like to have What can I do to achieve the 2 SEO goals above, **whether configuring, installing extra plugins or extending php code**?
1. Yoast SEO can have limitations for archive pages. Try a different SEO plugin such as Rank Math perhaps. Your other option would be to open the archive.php file of your theme and add your custom code in there if required. You may also contact the developers of that podcasting plugin to see if they have a solution. 2. That title is inserted through your theme. You can open the file archive.php and look for the insertion of headings. Change those headings in there but be aware that it will change on all archive pages/categories. For that reason it is advisable to modify it through your podcasting plugin.
stackexchange-wordpress
{ "answer_score": 2, "question_score": 0, "tags": "plugins, archives, seo, plugin wp seo yoast" }
Multiple Custom Taxonomy Rewrite I have registered two custom taxonomies of 'location' and 'type' registered before my post type of 'chalet' and have the rewrite rules set to 'slug' => 'chalets/%location%' 'slug' => 'chalets/%type%' 'slug' => 'chalets' respectively. The URL structure for archives that I need is: .../chalets/ .../chalets/[location term] eg /chalets/val-thorens .../chalets/[type term] eg /chalets/ski-chalet This works to a point but the second rule (whichever taxonomy is registered second) overrides the first and so the first subsequently returns a 404. How can I have both rewrites work or am I asking for the moon on a stick?
You must use separate base for both custom taxonomies. For example: default URL: /chalets/ location term URL: /chalets/location/%location% type term URL: /chalets/type/%type% Rewrite rules need to identify the requested custom taxonomy via URL. So, a base URL identifier is required in your case.
stackexchange-wordpress
{ "answer_score": 0, "question_score": 0, "tags": "custom taxonomy, rewrite rules, slug" }
How do I enable my Wordpress website RSS feed? My site doesn't seem to have an RSS feed I need the RSS feed on my site but it doesn't seem to have one. All the articles I've read say Wordpress sites have a default RSS feed so I must be doing something wrong. To try to find my feed, I've already tried: < < < < < < < All of the above simply refresh my site back to the homepage. I also tried Google FeedBurner with www.wowitinc.com and received: "We could not find a valid feed at that address." "The URL does not appear to reference a valid XML file. We encountered the following problem: Error on line 234: Attribute name "async" associated with an element type "script" must be followed by the ' = ' character." I have access to my cPanel but I really don't know what else to look for. I expect I need to add/modify some code. But can anyone advise where I should be looking and what I should do? I'm lost.
Yes, you have to edit the `functions.php` file of your theme. Try to find a `[themename]_setup` function (according to WordPress code conventions) inside the `functions.php` file of your active theme and add the following code in it: add_theme_support( 'automatic-feed-links' ); This code will add the RSS feed links to HTML `<head>` of all pages. You can find more information here: <
stackexchange-wordpress
{ "answer_score": -1, "question_score": 0, "tags": "rss" }
Get X post tags How to properly get only e.g. 3 post tags? My current code: $post_tags = get_the_tags(); if (!empty($post_tags)) { foreach ($post_tags as $tag) { echo '<a href="' . get_tag_link($tag->term_id) . '">' . $tag->name . '</a>'; } }
Your question seems similar to this one: how to limit and display tag? Based on it you can use this code to limit the tags: $post_tags = get_the_tags(); shuffle($post_tags); // use this incase you want to pick the tags randomly $count = 0; if ($post_tags) { foreach($post_tags as $tag) { $count++; echo '<a href="'.get_tag_link($tag->term_id).'">'.$tag->name.'</a> '; if( $count > 4 ) break; } } It will return 3 tags only.
stackexchange-wordpress
{ "answer_score": 0, "question_score": 0, "tags": "tags" }
Missing Page, But Still Exists In Preview A page went down and I get a "Page Not Found" error. I tried looking at all existing pages and the page is simply not there. It isn't in trash, either. However, when I created another page and hit "preview," I could suddenly navigate to the missing page, which works just fine. I inspected the page and the source reads "www.website.com/?p=480" alongside wp-content and wp-admin, etc. What is going on here? ((I was careful to copy the ?p=480 file content to notepad just in case it only exists inside of the cache))
It certainly sounds like a caching issue. Even if you disable **W3 Total Cache** , often it keeps cache code in your `wp-config.php` file and `.htaccess`. Purge all that code and see if the problem persists. Also, make sure your web host does not have server caching. Many "managed" platforms have a built-in cache (eg. WP Engine, SiteGround) which can lead to unusual behaviour. Purge or switch off any server cache you find. The other thing it could be is your permalinks. Go to the Permalinks page and just click "Save Changes" to force the permalink records in the database to be rebuilt. That should flush out any erroneous records.
stackexchange-wordpress
{ "answer_score": 0, "question_score": 1, "tags": "pages, 404 error" }
Update a previous version of plugin when the new plugin is built from the scratch I'm seeking help and suggestion from all of you. I've built a plugin from the scratch and now instructed to update the previous version of that plugin. But the new version that I've created is totally different from the previous version. The name of the files, folders, project structure and database(I've created few tables not using anything from the old) even the text-domain is changed. I've searched through the internet to see how update works and found wordpress maintains a svn repository and maintain a tag folder for versions. But I'm not sure if everything is changed will that work. What should I be concerned about updating a previous version of a plugin. I'm looking for you kind advice or solution here what would be the best for me in this situation so that the users can see a new version comes in and a single click will update their previous version. Thank you.
If you put your plugin in the WP Repository, and * change the version number in the readme.txt file * put the new code in a new 'tags' folder with the version as the folder name * also put the new code in the root of your repository (and I also put it in the 'trunk' folder * and do the SVN Update thing Then anyone with the plugin installed will get a notice about the update via the Admin, Update screen. And updating it will get the latest version installed on their WP system. I'd put some sort of notice on the Settings screen about the new version, in addition to the needed information in the readme.txt file , which is used to display text on the various pages on your WP plugin page.
stackexchange-wordpress
{ "answer_score": 0, "question_score": 0, "tags": "plugins, plugin development, updates, automatic updates" }
WordPress sitemap “Extra content at the end of the document” I have used WordPress with the plugin to generate a sitemap on request (in my case it was "All In One SEO Pack"). In the beginning, everything worked fine, but at some moment I found that the sitemap is not available. There was an error "Extra content at the end of the document"
It can be a problem with a too small value of `max_execution_time`. If your sitemap is too large, there is no enough time to generate it fully. Thus the document breaks in the middle. You can add `ini_set('max_execution_time', 10);` in `wp-config.php` or add `max_execution_time = 1` in `php.ini` Also, problem can be with extrace space before `<?php` or after `?>` in your `functions.php` file
stackexchange-wordpress
{ "answer_score": 0, "question_score": 0, "tags": "plugins, xml, sitemap" }
WordPress CPT custom custom label I want to edit the html output of the CPT page. Searched a lot but didn't find a solution ... May be I'm searching it wrong or it not might have done by anyone yet. ![enter image description here]( In the screenshot above one can clearly see the title Contest which is a label when I registered this post type. Its generating in `<h1>` tag. Either I want to edit the output or add a new element (i.e. and image) above it.
You can add anything up there with the 'in_admin_header' action. Example (pseudo code): add_action( 'in_admin_header', function() { if ( ... check $post_type, $pagenow etc, to target right page only ... ) { echo '<p>Hello editor</p>'; } } );
stackexchange-wordpress
{ "answer_score": 1, "question_score": 0, "tags": "custom post types" }
How to use do_shortcode_tag to modify the output of a shortcode? I would like to add shortcodes whose content gets processed by plugins before it gets displayed in the page. In particular, I have a plugin which processes content between two $ signs to produce math formulas and graphs. A simple shortcode is add_shortcode( 'test', 'test_sc' ); function test_sc( $atts ){ return "$\frac{15}{5} = 3$"; } By writing `$\frac{15}{5} = 3$` in a page this gets displayed ![]( By writing `[test]` in a page this gets displayed `$\frac{15}{5} = 3$` WordPress does a few things before the content from a page or post gets displayed on the site. For instance, it processes HTML paragraph (p) tags, it runs shortcodes and even sends the content to the theme and any plugins so they can do their thing to the content and include their bits. I heard that using `do_shortcode_tag` (reference) it is possibile to do full content processing, but how to do that?
You have a LaTex plugin? It probably filters "the_content". Try `return apply_filters( 'the_content', '$\frac{15}{5} = 3$' );`
stackexchange-wordpress
{ "answer_score": 1, "question_score": 0, "tags": "filters, shortcode" }
When does global/main code of plug execute? I am creating my first wordpress plug, and am using the WPBP template which is a great timesaver. In the main of the plugin (called myplugin.php), I added a simple command to write a line of text to a file. That works, however, when I refresh the page (one page of my website), I see approx 4 lines written to my file. Does the myplugin.php get included / execute many times for each page? If so, why? Next, what is the best way to enforce only running once per page. I plan to create a PHP object and don't want to create it 4 time. Obviously I could build my own detection if the class exists, but that seems wrong. Surely WP has devised some mechanism to ensure plugin global/main code only runs once.
Plugins are only loaded once per request. Plugins are loaded with this code: // Load active plugins. foreach ( wp_get_active_and_valid_plugins() as $plugin ) { wp_register_plugin_realpath( $plugin ); include_once( $plugin ); /** * Fires once a single activated plugin has loaded. * * @since 5.1.0 * * @param string $plugin Full path to the plugin's main file. */ do_action( 'plugin_loaded', $plugin ); } This is inside `wp-settings.php`, which only loads once, but also note that `include_once` is used, meaning that the plugin couldn't be loaded twice even if that code ran twice for some reason. However, not that I said _per request_. This means that any AJAX requests that are sent from the page will cause the plugin to be loaded for each of those AJAX requests, in the background. This could explain why the function is running multiple times
stackexchange-wordpress
{ "answer_score": 0, "question_score": 0, "tags": "plugin development" }
Possible for Category Base and Custom post Type to share the same slug/permalink? Rebuilding an author/writer website in WordPress. I have a custom post type of `books`. Working OK. I'd also like my category base to be `books`. Not working as yet. So a book URL would be like: ` And a category URL would be: ` How can I achieve this? > My workaround is a category URL like this (working using Category Base = `books/category`): > > ` Would prefer to add code in `functions.php` or `.htaccess` than use a plugin. Thanks
No, it's not safe to use the `/books/` URL for both a category base and custom post type base. WordPress uses the URLs to determine what type of content to serve. If you've set up 2 different types of content at the same URL, it won't have any way to know which you're requesting, and if you end up with a book slug that's the same as a category slug, you'll really have conflicts. To keep the URL types segregated but still logical, you could use URLS such as CPT: `example.com/book/title-of-a-single-book` Category: `example.com/books/category-name` Or, perhaps something like CPT: `example.com/books/title-of-a-single-book` Category: `example.com/book-categories/category-name` Or, continue using your workaround, `example.com/books/category/category-name`, and they will all appear to be under "books."
stackexchange-wordpress
{ "answer_score": 3, "question_score": 1, "tags": "custom post types, categories, permalinks" }
How do I list custom taxonomy terms with the links? I've the following code which gives the list of the portfolio category as text. What can I do to have them as links instead? thank you function thb_display_category_cus() { if ('portfolio' === get_post_type() ) { $categories = get_the_term_list( get_the_ID(), 'portfolio-category', '', ', ', '' ); if ($categories !== '' && !empty($categories) ) { $categories = strip_tags($categories); } echo esc_html($categories); } else { the_category(', ' ); } }
WebElain was correct but, you've also got the HTML escaped. The entire chunk of code should be: function thb_display_category_cus() { if ('portfolio' === get_post_type() ) { $categories = get_the_term_list( get_the_ID(), 'portfolio-category', '', ', ', '' ); echo $categories } else { the_category(', ' ); } }
stackexchange-wordpress
{ "answer_score": 1, "question_score": 0, "tags": "customization, categories, taxonomy, links" }
Convert comma separated list to serialized array to import as post meta I have a very site WordPress site that was custom built with custom tables for a membership system. I'm updating the site and trying to figure out how to re-upload the new fields as serialized data. For instance a "member" CPT has a custom field called "hours_of_operation". The data in that field is "Morning/Daytime". but I would like to get it to something like `a:2{{i:0;s:7:"Morning";i:1;s:7:"Daytime";}`. Other data is stored in other fashions, but I'm trying to piece a few together.
If you need to do this conversion in PHP, as part of whatever import process, then you can just convert the comma-separated values into an array with `explode()`, and then use `update_post_meta()`, which will automatically serialise the value for you: $value = 'Morning,Daytime'; $array = explode( ',', $value ); update_post_meta( $post_id, 'hours_of_operation', $array ); Use `trim()` if your comma separated values include, or could include, spaces: $value = 'Morning, Daytime'; $array = explode( ',', $value ); $array = array_map( 'trim', $array ); update_post_meta( $post_id, 'hours_of_operation', $array ); If, for whatever reason, you need to serialise the value yuorself in PHP, you can use `serialize()` to convert the array to a serialised string. $value = 'Morning,Daytime'; $array = explode( ',', $value ); $serialized = serialize( $array );
stackexchange-wordpress
{ "answer_score": 1, "question_score": 0, "tags": "custom post types, import" }
Woocommerce: Search by custom attribute I have created an attribute for products which is named: code. But default wordpress search functionality doesn't search code in front end. How I can modify it in order to include `code` in search ?
First verify your product attribute **(meta_key)** by running this query > Note: Change table prefix according to your wordpress database mine is default wp_ SELECT * FROM wp_postmeta WHERE meta_key LIKE '%code%'; /* get attribute name example (_sku, _stock, _stock_status, height, width )*/ Now add this to your functions.php file function Add_custom_search( $query ) { if( ! is_admin() && $query->is_main_query() ) { if ( $query->is_search() ) { $meta_query = $query->get( 'meta_query' ); $meta_query[] = array( 'key' => 'code', /* Product Attribute Meta key Here example (_sku, _stock, _stock_status, height, width ) */ 'value' => $query->query['s'], 'compare' => 'LIKE' ); $query->set( 'meta_query', $meta_query ); } } } add_action( 'woocommerce_product_query' , 'Add_custom_search' );
stackexchange-wordpress
{ "answer_score": 0, "question_score": 0, "tags": "woocommerce offtopic, search" }
The search engine of my website finds only posts and not pages, how can I solve this problem? I have a curious problem with the Wordpress search engine of my website (the one that makes URLs as ` When I installed Wordpress I noticed that when I used the search engine of my website, the results was only posts... it was as if the pages did not exist. Anyway, I don't know if that is normal for Wordpress blogs. After months, I was searching a word and I noticed that in the results the pages appeared! This amazing situation has continued for a lot of time but, from last week, inexplicably, pages don't appear in the results again. I told you the whole story to be clear, but my question is only one: How can I solve this strange behavior of my Wordpress search engine? For me it's very important that my users can also find pages.
WordPress search results can depend on your theme or plugins as well. Try enabling the default theme called Twenty Ninteen and then try your search. The default behavior is to search both, posts and pages. However if your theme is changing that you can force the search of pages. In order to search only pages in WordPress, we will need to add a PHP filter to the WordPress functions file. Open your functions.php file then copy and paste the code below. Your WordPress site will now return pages and posts in the search results. function SearchFilter($query) { if ($query->is_search) { $query->set('post_type', array('post', 'page')); } return $query; } add_filter('pre_get_posts', 'SearchFilter');
stackexchange-wordpress
{ "answer_score": -1, "question_score": 0, "tags": "php, query, search engines" }
show the author's role along with the name in the single.php some way to show the author's role in wordpress for example: Administrator, editor, author, contributor ect... Let something like this be left: This post was written by **_contributor_** JUan I'm just using `<? php the_author (); ?>` but I can't think of anything else to show the role of the user assigned to a post
To get author role in single.php you have to get author id first. Use following code to get author id $author_id = get_the_author_meta( 'ID' ); Then get userdata using $user = get_user_by( 'ID', $author_id); or you can use $user = get_userdata( $author_id ); now you can display role of author using : echo implode(', ', $user_info->roles);
stackexchange-wordpress
{ "answer_score": 0, "question_score": 0, "tags": "user roles, author" }