INSTRUCTION
stringlengths
11
999
RESPONSE
stringlengths
0
999
SOURCE
stringlengths
16
38
METADATA
dict
Redirect to previous page after login I'm using Profile Builder to create login page. My login page is: example.com/login/. I'm trying to redirect to previous page (the page user were before coming to example.com/login/). I have tried this code, but it doesn't work: add_filter('login_redirect', 'redirect_previous_page', 10, 1); function redirect_previous_page( $redirect_to ){ global $user; $request = $_SERVER["HTTP_REFERER"]; if ( in_array( $user->roles[0], array( 'administrator') ) ) { return admin_url(); } elseif ( in_array( $user->roles[0], array( 'subscriber') ) ) { return $request; } return $redirect_to; } Thank you for any help.
It seems it is not possible with this version of profile builder.
stackexchange-wordpress
{ "answer_score": 0, "question_score": 0, "tags": "login" }
Hide image on homepage I want hide images on excerpts only on the homepage of my blog and only when the screen resolution is under 480px. Is it possible to do this ? I know I can set an CSS propriety for the width but I don't know how to specifiy only for me homepage, maybe with a function ? @media only screen and (max-width : 320px) { } Thank you !
use the default WordPress `.home` class(it is a part of the `body_class()` function that is added by default to every `body` html tag): @media screen and (max-width : 320px) { .home .your-featured-image { display: none; } } <
stackexchange-wordpress
{ "answer_score": 0, "question_score": 0, "tags": "css" }
Google Map not displayed I'm setting up a website and I'm using Avada Theme. I'm using avada's builder to insert a Google Map but it won't show. I get this: ![enter image description here]( Does anybody know what's going wrong?
It might be that you haven't set your Google Maps API key. Or, if you have already set an API key then it might be due to any restrictions that you may have set for the API key such as restricting it to a specific domain. You can obtain a Google Maps API key from here: <
stackexchange-wordpress
{ "answer_score": 0, "question_score": -2, "tags": "google maps" }
Can you change the color of svg icons to the global color I choose from Wordpress For example If I make svg icons that are grey and violet, when I change the global color scheme on wordpress, Is it possible to make it work so if the main color scheme was violet, and I change the global color from violet to yellow, the icons become grey and yellow, Is such thing possible? Will SVG´s had to be in the HTML (php wordpress template) page for this or this can be CSS? Thanks
Yes, you can alter the colour of svg paths using css, BUT (and it's a big but, I cannot lie), only if the svg code is printed inline and not linked via an `<img />` element. For example (and this is just a line of css from one of my sites): `.logo g path { fill: #fff; }` Both `g` and `path` are svg elements, which is why you might not recognise them, and `fill` is the svg equivalent of `background-color`.
stackexchange-wordpress
{ "answer_score": 1, "question_score": 0, "tags": "css, svg" }
How can I remove the user avatar from admin toolbar? In the admin toolbar, I want to remove the avatar from the 'logged in as...' dropdown.
You can try this :) add_action( 'admin_bar_menu', 'remove_my_account', 999 ); function remove_my_account( $wp_admin_bar ) { $wp_admin_bar->remove_node( 'user-info' ); } Screenshot: <
stackexchange-wordpress
{ "answer_score": 3, "question_score": 1, "tags": "wp admin" }
Notifications on Wordpress Website I am working on a wordpress website where users can register and post things that they would like to promote or anything that they like to post. Now how can i enable notifications for the user whenever someone comments on their posts or like their posts or anything?
Try BuddyPress. It covers majority of your functionality. Or you can go with custom approach using Custom PHP script and AJAX with custom tables created in Database. Here is a link to such tutorial. < * * * **EDIT :** I don't know what approach you are following. But considering you are using Wordpress Post and Comments. Create a DB table for storing notifications. Click here for a DB schema Try using **'comment_post'** action. And in that function you can get `POST_ID` based on `COMMENT_ID` & then you can get `POST_AUTHOR` based on `POST_ID`. Create entry in the notification table mentioned above. You can also send him/her an email as well. Now when a User logs in. you can fetch entries from Notification table and show it on your web page. This is just the approach i gave you. For proper execution you can follow the blog post mentioned above and combine it with this approach.
stackexchange-wordpress
{ "answer_score": 0, "question_score": -1, "tags": "plugins, posts, notifications" }
Redirect guest if he tries to access a specific page While I'm developing a website and doing some testing I would like to block access to non-admin (and eventually non-editors) to specific pages such as the woocommerce shop and related pages. Is there a way, without using plugins, in the `functions.php` to check: $list_of_blocked_pages = [ 'shop', 'cart', 'checkout', 'etc...' ]; if ( current_page_is_in( $list_of_blocked_pages ) && !admin && !editor ) { redirect_to_page( $url ); }
You can use template_redirect action to redirect Specific users based on your terms. This action hook executes just before WordPress determines which template page to load. It is a good hook to use if you need to do a redirect with full knowledge of the content that has been queried. You can use is_page function to check weather the current page is in your list of pages or not. add_action( 'template_redirect', 'redirect_to_specific_page' ); function redirect_to_specific_page() { if ( is_page('slug') && ! is_user_logged_in() ) { wp_redirect( ' 301 ); exit; } }
stackexchange-wordpress
{ "answer_score": 5, "question_score": 1, "tags": "redirect" }
Is it possible to make a custom post that adds multiple pages? I'm trying to make a custom post for an event that contains multiple pages like this event page. Whenever someone would add an "event" an event homepage, agenda page, venue page, and registration page would be generated. Is this possible and does it make any sense to do it rather than having a separate page template for each one and linking them? If it is possible, where are some good resources to read up on this. My impression from the WordPress docs is that it is impossible - but I'm not sure. Thanks!
One option would be to set up a MultiSite. That way each "subsite" is for one event, and when the subsite is created you can programmatically create each Page needed. It just depends on your exact needs whether or not this would be overkill. If you need to have all events linked in some way - such as a central calendar - you probably want to set up a Custom Post Type of "event" and make it hierarchical, so you can have each event as a top-level (parent) post, and set the agenda, registration, and venue pages as children. Really the only benefit to having these as a custom post type rather than a page would be to keep them separate from other content types. If you do anything fancy like adding event schema it's also easier to add this to a CPT than it is to a generic Page.
stackexchange-wordpress
{ "answer_score": 0, "question_score": 0, "tags": "posts, customization" }
Get author Meta for particular user inside the loop I am using this code to get the meta for the current author in the loop. get_avatar( get_the_author_meta( 'ID' ), 120); How can I modify this to get the meta for a particular user ID? I tried for example to get the image for userID: 4 but this didn't work. get_avatar( get_the_author_meta( '4' ), 120);
The function `get_the_author_meta('ID')` will return the ID of the author for the current post. That means this line should work. `get_avatar( get_the_author_meta( 'ID' ), 120);` This will not work get_avatar( get_the_author_meta( '4' ), 120); Because you are trying to get a property named '4' inside the user object and that property doesn't exist. If you wanted to get the avatar for user 4 you would use. get_avatar( 4, 120); Because get_avatar takes either a `$user_id` or `$email` as the first parameter and the `$size` as the second. On a final note the WordPress documentation uses, so check for a formatting error in your html. get_avatar( get_the_author_meta( 'ID' ), 32 );
stackexchange-wordpress
{ "answer_score": 2, "question_score": 0, "tags": "loop, user meta" }
show shop instead of 404 page for missing products How should I show the shop instead of a 404 page when a product is missing? Currently users get a 404 page which makes them loose interest. I use woocommerce with wordpress on a server with nginx.
`// Missing product redirect to product category add_filter( 'rewrite_rules_array', function( $rules ) { $new_rules = array( 'shop/([^/]*?)/page/([0-9]{1,})/?$' => 'index.php?product_cat=$matches[1]&paged=$matches[2]', 'shop/([^/]*?)/?$' => 'index.php?product_cat=$matches[1]', ); return $new_rules + $rules; } );`
stackexchange-wordpress
{ "answer_score": 1, "question_score": 1, "tags": "woocommerce offtopic, 404 error, nginx" }
How to change role of all users with a specific role to another role? what function can be used to change user role of all users who are currently assigned the role "Customer" to "Editor"? Basically I need to create a cron job doing this daily. I have figured out the cron job part but need help with how to change roles via function.
Use the following function: function wpse_replace_user_role( $from, $to ) { $args = array( 'role' => $from ); $users = new WP_User_Query( $args ); if ( !empty( $users->get_results() ) ) { foreach( $users->get_results() as $user ) { $u = new WP_User( $user->ID ); $u->remove_role( $from ); $u->add_role( $to ); unset( $u ); } unset( $users ); } } * _$from_ \- query all users with this role * _$to_ \- role to be set instead, for each queried user
stackexchange-wordpress
{ "answer_score": 1, "question_score": 3, "tags": "user roles" }
How to check if an action is already fired? How to check if an action is already fired in a function for example: function foo() { // checking if the action 'wp' is fired if( !action_fired('wp') ) { trigger_error('invalid call'); return; } if( is_front_page() ) { // Do something } } I want to check that because: 1. WordPress conditional tags like `is_front_page` won't work being called before the 'wp' hook. 2. Still, these conditional tags can be called before 'wp' without any warning or notices So writing a function like `foo()`, I want to ensure it is called properly by throwing an error if the 'wp' action hasn't fired at that time.
> How to check if an action is already fired? The `did_action( $tag)` function returns the number of times the `$tag` action hook has fired.
stackexchange-wordpress
{ "answer_score": 4, "question_score": 3, "tags": "actions, conditional tags" }
Add item to top of menu using a filter in functions.php I want to add a logo to my main menu. I am using this function: add_filter( 'wp_nav_menu_items', 'add_logo_to_menu_item', 10, 2 ); function add_logo_to_menu_item ( $items, $args ) { if ($args->menu == 'main-menu') { $items .= '<li><a href="#"><img src="PATH_TO_IMAGE"></a></li>'; } return $items; } The problem I am having is I want the logo to be at the top of the menu. This filter currently places it in the last position of the menu. Any ideas?
Use `$items = 'Blah'.$items` instead of `$items .= 'Blah'` add_filter( 'wp_nav_menu_items', 'add_logo_to_menu_item', 10, 2 ); function add_logo_to_menu_item ( $items, $args ) { if ($args->menu == 'main-menu') { $items = '<li><a href="#"><img src="PATH_TO_IMAGE"></a></li>' . $items; } return $items; }
stackexchange-wordpress
{ "answer_score": 3, "question_score": 0, "tags": "php, functions, menus, filters, menu order" }
Disable New User Registration Email sent to Wordpress admin email on 4.9.5 I don't know if something changed, but I'm not able to disable the email sent to the WordPress admin mail. I tried adding this code to my theme's `functions.php` file //disable default WordPress new user notification emails if (!function_exists('wp_new_user_notification')) { function wp_new_user_notification( $user_id, $deprecated = null, $notify = '' ) { return; } } And tried enabling the < plugin. But the mail keeps being sent to the admin.
the function wp_new_user_notification is one of the Pluggable Functions. In the documention you can read: > Pluggable functions were introduced in WordPress 1.5.1 These functions let you override certain core functions via **plugins**. The most up-to-date list of core functions that WordPress allows plugins to override is available at wp-includes/pluggable.php. WordPress loads the built-in functions only if they are undefined after all plugins have been loaded. That means you can not override that function in your theme. Put it in an plugin and it should work. Usefull links: How to override pluggable function in theme? - wordpress.stackexchange.com
stackexchange-wordpress
{ "answer_score": 3, "question_score": 0, "tags": "user registration, notifications" }
Dynamic data in `wp_register_script` needed I'm using `wp_register_script` and `wp_enqueue_script` in `functions.php` is like this: function add_wp_scripts() { wp_register_script( 'myscript', get_template_directory_uri() . '/jsfile.js', array(), null, true ); wp_enqueue_script('myscript'); } add_action( 'wp_enqueue_scripts', 'add_wp_scripts' ); This works fine. The `jsfile.js` contains just two static hard coded data that do not change often. Now I have to evaluate if it is possible to get dynamic data from database and to put this data into `jsfile.js`? - Since yet,I have no experience with JavaScript and I would like to know if it possible get dynamic data in `jsfile.js`? If yes, how could I realize this and are there any restrictions from WordPress itself?
You are looking for the `wp_localize_script()` function. This function allows you to add data from server to your javascript. However, this will not change the content of `jsfile.js`. Instead, it will add some global variable in your theme's footer.Changing the content of a JS file before outputting it to the browser is an advanced technique, and requires compiling/buffering. The above function should be enough for most of the users. Everything you need about how to use the function is included in the provided link.
stackexchange-wordpress
{ "answer_score": 1, "question_score": 2, "tags": "database, javascript" }
Using WP_Query for categories instead of get_terms I have managed to get all parent categories from Woocommerce with this function $terms = get_terms( array( 'taxonomy' => 'product_cat', 'hide_empty' => false, 'parent' => 0 ) ); But I haven't managed to do the same with **WP_Query**. Now I have 2 questions: 1. How can I do the same - getting a list of categories from Woocommerce - with WQ_Query 2. Is it recommended to use WP_Query over get_terms? Thanks.
$category_detail=get_the_category(get_the_ID());//$post->ID foreach($category_detail as $cd) { $name_cat=$cd->cat_name; $id_cat=$cd->term_id; } try now this code
stackexchange-wordpress
{ "answer_score": 1, "question_score": 0, "tags": "wp query, terms" }
Setting a value on existing tag metadata field when that tag was just created by a user I have extra metadata (true/false) for taxonomy terms. What I'm trying to accomplish is give this field a value for new terms created by users (it doesn't matter if that value is true or false, just matters theres a value). This tag metadata field would act as a "flag" for these term, letting me know that they were created by someone other than me. I then would be easily able to prevent those terms from being loaded again for other users before I looked at them. You could think of it as quality control.
to add a meta value on a term creation, you can use that : const TAXONOMIE_SLUG = "category"; add_action("create_" . TAXONOMIE_SLUG, function ($term_id, $tt_id) { $user = wp_get_current_user(); update_term_meta($term_id, "creationUser", $user->ID); }, 10, 2);
stackexchange-wordpress
{ "answer_score": 3, "question_score": 1, "tags": "tags" }
where to add redirection rewriterule in .htaccess file? I use the redirection plugin which can give me the rewrite rules in this format as output: # Created by Redirection # Sun, 06 May 2018 09:25:01 +0000 # Redirection 3.2 - <IfModule mod_rewrite.c> RewriteRule ^abc$ /123/ [R=301,L] </IfModule> # End of Redirection My current .htaccess file is standard: ![enter image description here]( Where should I add the direction code from the plugin into the .htaccess file? Should I add it first or last, or somewhere in the existing rule-set? Thanks!
Your external redirect needs to go at the very top of your `.htaccess` file, before the WordPress front-controller (ie. before the `# BEGIN WordPress` section). If you place it at the end of the file then it will simply never get processed, because the WordPress front-controller routes all URLs and then stops further processing. If you place it inside the `# BEGIN WordPress` block then WordPress is likely to (try to) overwrite this in a future update. _Aside:_ You don't need the `<IfModule mod_rewrite.c>` wrapper. You already know that mod_rewrite is enabled on your server (or not) and presumably this redirect is mandatory?
stackexchange-wordpress
{ "answer_score": 0, "question_score": 1, "tags": "htaccess, redirect" }
How can I show a tag description, using 'slug' rather than 'id' I'm currently using 'echo tag_description()' to show a tag description. Is there an alternative whereby I can use the tag slug rather than ID?
You need to get the tag ID first. You can get the tag ID from the slug using the `get_term_by()` function: $tag = get_term_by( 'slug', 'tag-slug-here', 'post_tag' ); echo tag_description( $tag->term_id );
stackexchange-wordpress
{ "answer_score": 0, "question_score": 0, "tags": "tags" }
Change background image in PHP I have a post with the featured image. On my homepage, I want to display the featured image and the post title. But, in media screen < 576px , I want to display only the post title and "NO" featured image. Please see my code below (example) : <div style="background-image:ulr('<?php the_posts_thumbnail_url(); ?>')" class="myPost"> //some code here </div> This code above work fine. I just want to ask how to delete background image in media screen < 576px. Thanks for your anwsers.
You won't be able to delete the image per se, but using CSS you can hide the image. You should also make sure you fix the typo inside of your inline style it should read `background-image: url(...)`. For the varying styles, you can utilize media queries to hide at a certain point. I don't recommend using `!important` but it will be the only way to override this inline style using CSS. @media screen and (max-width: 576px){ .myPost{ background-image: none !important; } }
stackexchange-wordpress
{ "answer_score": 2, "question_score": -1, "tags": "post thumbnails" }
How to Include Fields in Query String When Making Request of WordPress.org Plugin API? I am running a query against the WordPress.org Plugin API that looks like this went built: > [ This works great. Now I want to reduce the amount of data that is being returned in each request by passing in fields that shouldn't be displayed like so: > [ Problem is, this doesn't work. I still get back the description field. Any ideas on what I'm doing wrong?
HT to otto42 on the WordPress Slack who pointed out that false might be evaluating as true and to instead try using 0...which I did and it worked: [
stackexchange-wordpress
{ "answer_score": 1, "question_score": 0, "tags": "plugins, api, query string" }
Prevent Archive URLs My Wordpress site goes looking for an archive page if I append a year after the URL. For example: `http:/mysiteurl.com/my-site/2018`. If there are posts from this year, it ends up redirecting to `index.php` for some reason. If there are no posts from that year, it goes to 404 page which is what I want. For example: `http:/mysiteurl.com/my-site/2014` goes to a 404 page because there are no posts from that year, which is what I want. My permalink structure is set to **Post name** which is like this `http:/mysiteurl.com/my-site/sample-post/`. So typing a year after the URL **should** display a 404 page, **not** show me archives. Why is this happening?
WordPress generates date archives automatically, it's just a thing it does. You see the `index.php` template probably because there isn't a more specific one for date archives in your current theme. There are plugins that disable these archives, Yoast SEO is one. A quick fix is to empty the date archive rewrite rules: add_filter( 'date_rewrite_rules', function( $rules ){ return array(); } ); Visit the **Settings > Permalinks** page after adding this to flush rules.
stackexchange-wordpress
{ "answer_score": 0, "question_score": 0, "tags": "posts, permalinks, url rewriting, urls, archives" }
edit_page or edit-pages for current_user_can()? The more I read Wordpress Codex the more often I wonder if tutorials you can find on the net are actually correct. I've found several tutorials about creating metaboxes where user capabilities (when saving the matabox) are being checked like this: if ( 'page' === $_POST['post_type'] ) { if ( ! current_user_can( 'edit_page', $post_id ) ) { return $post_id; } } elseif ( ! current_user_can( 'edit_post', $post_id ) ) { return $post_id; } When I was browsing through Codex page on WP Capabilities I couldn't find `edit_post` or `edit_page` capability. There were `edit_posts` and `edit_pages` capabilities mentioned on that page. Why there is `edit_post` instead of `edit_posts` used in the bit of code I pasted?
You can find list of capabilities here: Roles and Capabilities There is no capability called `edit_post` nor `edit_page`. But... There is also something called Meta Capabilities. The capabilities listed on the Capabilities list are global capabilities. So they're saying that user can edit posts or pages. But it doesn't mean that given user can edit given post (for example editors can edit only own posts). This is where meta capabilities are used.
stackexchange-wordpress
{ "answer_score": 1, "question_score": 0, "tags": "metabox, capabilities" }
Custom Search | check multiple meta_value for search value I am going to split up my following question in two sections and make it more neutral, so people can look it up and find it if they have the same question, rather than making it too specific ... I am trying to build a search for something location based and want people to be able to search either ZIP, Town, County or State in one single field. My custom `post_type` has multiple `meta_keys` which I want to search for with one single search field. As example: `post_type` = `location_type` | `meta_key` = `zip` | `meta_key` = `town` | `meta_key` = `county` | `meta_key` = `state` | Now, what I want to do is, I want to search if EITHER or MORE of these fields contains the search value and want to query all applying posts, displaying the custom-posts meta_key value for Profession `meta_key` = `profession`.
You can use meta query as give below: $args = array( 'post_type' => 'location_type', 'posts_per_page' => 10, 'post_status' => 'publish', 'meta_query' => array( 'relation' => 'OR', array( 'zip' => 'zip-value' ), array( 'town' => 'town-value' ), ), );
stackexchange-wordpress
{ "answer_score": 1, "question_score": 0, "tags": "custom post types, custom taxonomy, search, sql" }
WP_Query Date Query After Minus Hour AND minus minutes Can't really find information on this and nothing I've tried is working. Before I had it as, $args = array( . . . . . . . . 'date_query' => array( 'after' => '-4 hour', 'inclusive' => true ) ); Worked fine. But now I'm trying to make it after `-3 hour` and `-30 minute`.. How do I do this? 'date_query' => array( 'after' => array( 'hour' => '-3', 'minute' => '-30' ), 'inclusive' => true doesn't work 'date_query' => array( // 'after' => '-4 hour', 'after' => array( '-4 hour', '-30 minute' ), 'inclusive' => true ) doesn't work.. I'm sure it's something simple. Anyone know the solution?
Here's one way translating it to _minutes_ only: $args = [ 'date_query' => [ 'after' => '270 minutes ago', // <-- 4 hours and 30 minutes ago 'inclusive' => true ] ];
stackexchange-wordpress
{ "answer_score": 3, "question_score": 1, "tags": "wp query" }
redirect if shortcode exists WordPress beginner here. I'm trying to check if a shortcode exists in the page being requested by the user, then if it does, redirect if the user is not signed in. function redirect_to_home() { if (has_shortcode(get_the_content(), 'shortcode')) { if(!is_admin() && !is_user_logged_in()) { //redirect exit(); } } } add_action('template_redirect', 'redirect_to_home'); Is this close? And currently this code is placed in the functions.php files, is this correct?
If you look at the source code of `add_shortcode` you will see this function doing little more than store the name of the shortcode in a global array. So, checking if a shortcode exists means looking it up in the array. Hence, if you want to check for a specific shortcode in `the_content` you must be sure that shortcode has already been added at the point you need it. Else `has_shortcode` will say it doesn't exist. Luckily, looking at the hook order, you see `template_redirect` being executed after `after_setup_theme`, the default hook to load theme related stuff. If you use that hook to add your shortcode (in `functions.php`), you can be sure your shortcode exists by the time you get to `template_redirect`. So, yes, you are on the right track. You're using the right hook and the data you need is available at that point in WP's execution order.
stackexchange-wordpress
{ "answer_score": 1, "question_score": 0, "tags": "shortcode, redirect, user access" }
How unrequire comment text in wordpress post I made a few comment meta field and they work well. Now I need to set comment text as no require. I found this solution but don't work for me. add_action( 'pre_comment_on_post', 'allow_empty_comment_text' ); function allow_empty_comment_text( $text = '' ) { if ( ! isset ( $_POST['comment'] ) or '' === trim( $_POST['comment'] ) ) { $img = '/* Process uploaded image here, create an <img> tag. */' $_POST['comment'] = '<img>'; // use a real img tag here } } any solution please.
I solve it: step 1 - insert a random number in text body, because WordPress prevent users that duplicate comments. step 2- set display:none to textarea of comment field Finally copy this code in functions.php: add_filter( 'comment_form_field_comment', 'set_default_comment_text', 10, 1 ); function set_default_comment_text() { $post_id = get_the_title(); global $current_user; get_currentuserinfo(); $comment_rand = rand(10,100000); $comment_field = '<textarea style="display:none" id="comment" name="comment" cols="45" rows="8" maxlength="65525" readonly="readonly">'.$comment_rand.'</textarea>'; return $comment_field; }
stackexchange-wordpress
{ "answer_score": 1, "question_score": 1, "tags": "comments" }
.htaccess Redirect I am using the following permalink structure: /%postname%-%monthnum%%year%%post_id%.html I want to get it changed to just `/%postname%/`. Please help me with what should be the correct redirect rule for `.htaccess`.
Assuming you have changed your permalinks in WordPress (under Settings > Permalinks), as mentioned earlier, then you can redirect your old URLs en masse (in order to preserve SEO) with something like the following at the top of your `.htaccess` file, using mod_rewrite: RewriteRule ^([\w-]+)-\d{7,}\.html$ /$1/ [R=302,L] This will redirect URLs of the form `/%postname%-%monthnum%%year%%post_id%.html` to `/%postname%/`, assuming your _post name_ is limited to the characters `A-Z`, `a-z`, `0-9`, `_`, `-`. As noted above, this must go _before_ your WordPress front-controller (ie. before the `# BEGIN WordPress` section), at the top of your `.htaccess` file. Note also, that this is currently a temporary (302) redirect. Change the `302` to `301` (permanent) only once you have tested that this is working OK. This is to avoid any problems with browser caching.
stackexchange-wordpress
{ "answer_score": 1, "question_score": 1, "tags": "redirect, htaccess" }
Wordpress change Language not working My issue is, that I want to change the Language to German (de_CH) and BBPress etc. should change the language too. I know not all Plugins are available in German. However whatever I do, add them manually, add them with Loco Translate plugin, or trying to switch the language in the General Wordpress settings, it will not change anything. I very much assume that I have all the permissions set correctly on my server because I did it as the documentation of Wordpress tells me. Does anyone have a clue what could be the issue? (I can, however, change the Wordpress language itself without a problem)
bbPress doesn't have a **de_CH** translation available. All available languages for bbPress are listed here with the translation progress:<
stackexchange-wordpress
{ "answer_score": 0, "question_score": 1, "tags": "plugins, code, language, bbpress" }
WordPress theme logo handling (Trying to use GIF as logo) I am trying to use a GIF as a logo on a WP site but all I can get is a still image. I read a lot about it and it seems the issue is that the theme resizes the GIF which destroys the animation. Where can I find the logo size settings and is it enough to change them in a child theme or is there more to it? I thought the logo settings chould be in the file `header.php` but my `header.php` is almost empty, with the exception of the following code: <?php /** * @package vogue * @since 1.0.0 */ // File Security Check if ( ! defined( 'ABSPATH' ) ) { exit; } get_template_part( 'header-single' ); get_template_part( 'header-main' ); So I am back to square one. How can I locate and change the logo size settings?
Since this is a theme-specific question it would be better to ask the theme's author/support team directly. As you can see from `header.php` your theme uses template parts. The `header-main.php` file is the most likely one to contain the logo since its name implies it would be used sitewide. You are most likely looking for code that looks something like this: `get_theme_mod('custom_logo'), 'medium')` or `if(has_custom_logo())` or `the_custom_logo()` generally - something to do with `custom_logo`. When you find the call to `custom_logo` it will probably specify `medium` or some other image size. You want to change whatever image size the theme is using to `full` which in most cases will display the full, un-resized version you uploaded. Once you've done that, you may also need to edit some CSS since that can also affect the size the image is displayed at - though not the actual, underlying file.
stackexchange-wordpress
{ "answer_score": 1, "question_score": 0, "tags": "themes, logo" }
Theme keeps going to default files Theme files go back to default, deleting my custom templates I have created. I have a back-up, but it does it once a day. Anyone run into this before, is it a backup issue?
If you're editing the theme directly it might be because of an update, when a them updates it deletes all the changes you have made on it. If you want to edit themes you have to create a child theme Just create a folder next to your actual theme folder ( _wp-content/themes_ ) with the name you want for your child theme and create the style.css file with the **Template** option of your stylesheet header pointing to your actual theme (write there the name of your actual theme folder). To make any changes just copy teh page you want to modify from your theme folder to your child theme folder and edit it there. That way the changes will remain after the update
stackexchange-wordpress
{ "answer_score": 0, "question_score": 0, "tags": "templates, customization" }
How to save data in my db table with using contact form seven? I have a lot of input field and I'm using contact form seven. but let me know how to save the values of all fields in my db
Use Post My Contact Form plugin extension. You can map your form to a custom post or an existing post type, and map individual form fields to custom post fields. This is a lot more practical than CF7 Database as it allows you have each form submissions stored as a post and therefore reuse the WordPress functionality and admin dashboard to further manage your submitted data.
stackexchange-wordpress
{ "answer_score": 0, "question_score": -1, "tags": "plugin contact form 7" }
Rest API rename media I've been able to upload images using the REST API but the names are wrong right now and I was thinking to go through all of the products I have and rename the images. Since I have more than 500 products seems like it could use some automation. Is there a way to update the filename on a media entity? Not talking about the title which is something else and that can be easily done. I've seen plugins but they go one by one which is undesired. Any hints?
After much digging, it doesn't seem to be possible. I did craft some automation with a Node script that basically does this: * Check if the name is correct. * If it's not, then download the image, upload with a new name and update the product. If everything goes smooth, delete the original image. * Same is repeated for every variation the product might have. It's a bit cumbersome but effective.
stackexchange-wordpress
{ "answer_score": 1, "question_score": 1, "tags": "media, media library, rest api" }
Does rename of page slugs create 301 redirects from old slug to new (same as for posts)? Does rename of page slugs create 301 redirects from old slug to new (same as for posts)? Starting a fresh install of wp `wordpress:4.9.4-php7.1` I'm trying to get automatic redirects for renamed page permalinks working. 1. Creating a page with permalink `/a` 2. Rename that page permalink to `/b` 3. I expect GET `/a` to return a 301 redirect to `/b` Creating a post with slug `a` and then renaming it to `b` creates a 301 redirect from `a` to `b` and a row in the `wp-postmeta` table with `meta_key=_wp_old_slug` and `meta_value` with the old slug. Is this supposed to work for pages as well? I think I've had a setup where this works before but now I'm not sure anymore. Is there a default redirect system like this that would also work when changing parents of a page?
Pages are, from the underlying engine's point of view, posts with a `post_type` of `page`. So you should ideally see the same redirects. However, you may find a plugin like Redirection solves your issue more completely.
stackexchange-wordpress
{ "answer_score": 1, "question_score": 1, "tags": "permalinks, redirect, slug" }
Where is custom template file chosen for a post stored in the DB? Where is the custom template file that has been selected through the wordpress edit screen (for a post or page) stored in the wordpress database?
It's in the post meta table (usually `wp_postmeta`), with the page id in post_id, meta_key with `_wp_page_template` and meta_value with the template file name.
stackexchange-wordpress
{ "answer_score": 8, "question_score": 4, "tags": "database, admin" }
posts_per_page => 1 shows 2 posts I am trying to add a button to take the viewer to a random post. Below's the code I am using:- <?php query_posts(array('orderby' => 'rand', 'posts_per_page' => 1)); if (have_posts()) : while (have_posts()) : the_post(); ?> <div class="post-lot"> <a href="<?php the_permalink() ?>">Yes, Robo! Take me there.</a> </div> <?php endwhile; endif; ?> But, it keeps showing two links. If I change `posts_per_page` to 2, it shows 3 links. I tried adding `wp_reset_query` but the issue still persists.
Most probably you have a sticky post there. If you want exact number of posts you need to ignore sticky posts. So your query should look like this: query_posts( array( 'orderby' => 'rand', 'posts_per_page' => 1, 'ignore_sticky_posts' => 1, ) ); or as suggested, never use `query_posts()` $query = new WP_Query( array( 'orderby' => 'rand', 'posts_per_page' => 1, 'ignore_sticky_posts' => 1, ) );
stackexchange-wordpress
{ "answer_score": 7, "question_score": 1, "tags": "query posts" }
How do I conditionally defer scripts based on the page name? I have the following code in functions.php. The first function correctly enqueues the script based on the page name. However, the second function always adds the 'defer' attribute. function custom_scripts() { global $page; if ($page->page_name !== 'awkward_page') { wp_enqueue_script('jquery'); } // ... } add_action( 'wp_enqueue_scripts', 'custom_scripts' ); function defer_scripts( $tag, $handle ) { global $page; if ($page->page_name !== 'awkward_page') { return str_replace( ' src', ' defer src', $tag ); } return $tag; } add_filter( 'script_loader_tag', 'defer_scripts', 10, 2 ); What is wrong with this code? If this is the wrong way to conditionally add the 'defer' html attribute, what is the correct way?
The global `$page` variable is not a `WP_Post` object. It is just the post ID. So to get the page title, you need to get the `WP_Post` object first from the post ID. The reason that defer is always getting added is two-fold. First, `$page` is an integer, so `$page->page_name` will evaluate as `null` and `null` is not identically equal to 'awkward_page'. It will also throw an error or warning. Also, `page_name` is not a valid property of a WP_Post object. The correct property is `post_name` \- even on pages. function defer_scripts( $tag, $handle ) { //* Get the post object $page = get_post( get_the_ID() ); //* Defer on some condition if( 'awkward_page' !== $page->post_name ) { $tag = str_replace( ' src', ' defer src', $tag ); } return $tag; } add_filter( 'script_loader_tag', 'defer_scripts', 10, 2 );
stackexchange-wordpress
{ "answer_score": 1, "question_score": 0, "tags": "theme development" }
Fix Characters Wordpress Ionic App Special Characters in my ionic App are displayed weird. For example when I have a quote in my title (headline) it's displayed as follows: `&#220;` for opening" and `&#221;` for a closing" I have changed already in my wordpress the following /** Database Charset to use in creating database tables. */ define('DB_CHARSET', 'utf8'); /** The Database Collate type. Don't change this if in doubt. */ define('DB_COLLATE', ''); to: /** Database Charset to use in creating database tables. */ //define('DB_CHARSET', 'utf8'); /** The Database Collate type. Don't change this if in doubt. */ //define('DB_COLLATE', ''); Purged all Cache but the problem is the same. Anybody an idea?
OK after doing excessive research I came to the conclusion that I have to add `[innerHTML]` into the span/title/h1
stackexchange-wordpress
{ "answer_score": 0, "question_score": 0, "tags": "rest api, json" }
how to get post slug from url in wordpress i want to send post slug through URL and get on other page. e.g, www.example.com/cars/mini-car how can i get ' **mini-car** ' car type i've found the way to get the id from url. that is; $url = get_post_permalink(); //Get the url of the current post $substring_start_pos = strpos($url, 'pid=') + 4; //Find the position in $url string where the url number starts $url_number = substr($url, $substring_start_pos); //Extract the substring form the start position to the end of the url string $key_1_values = get_post_meta($url_number, '_song_name', true ); echo "Your song is called $key_1_values"; i want to know how can i do with custom url (to get post slug of custom post type sent from previous page) like i mentioned as example
You can use **get_queried_object()** which holds the current queried object from where you can get the page slug which is held by the post_name property. You can use as: if ( is_page() ) // // Get the page slug using queried object $my_slug = get_queried_object()->post_name; Hope this will help you.
stackexchange-wordpress
{ "answer_score": 2, "question_score": 1, "tags": "custom post types, menus" }
How do I change the <title> element using a custom function? I am trying to add meta titles via the Yoast SEO plugin. My theme is not compatible with this -- the resulting `<title>` tag is a concatenation of the Yoast title and the theme's title. One solution is to ensure the `<title>` tag in `header.php` is set to `<?php wp_title(''); ?>` (see Yoast article here \-- section "Themes without title-tag Support"). This method works (I tested it), and is also the solution suggested to me by my theme devs. But how can I do this via a custom function in my child theme's functions.php, rather than editing header.php? I realize one possible solution is to copy header.php from parent theme to child theme, then edit that file. But I’m trying to avoid that if possible. I tried the answer given in this previous question, but all that did was add a second `<title>` tag to the page, in addition to the existing, incorrect `<title>`.
If an incorrect `<title>` tag has been added to the header _template_ the only option that will work is the child theme method. You can't override template markup with a custom function. If you do use a child theme then don't use `wp_title()`, just remove the title tag entirely and register support for support `title-tag`.
stackexchange-wordpress
{ "answer_score": 1, "question_score": 0, "tags": "customization, plugin wp seo yoast" }
Running Gutenberg React in Development Mode Is there a way to enable WordPress to run the non-minified version of React while developing Gutenberg blocks? I am receiving an error from React while learning to create Gutenberg blocks. react-dom.min.b75d8b30.js:62 Error: Minified React error #130; visit for the full message or use the non-minified dev environment for full errors and additional helpful warnings. It would be very helpful to get the full error. I am using the Gutenberg suggested abstraction, `wp.element.createElement` in order to create the elements. So my plugin has no direct access to React.
It took me way too long to find this but all you have to do is set SCRIPT_DEBUG to true. Simply add this line to wp-config.php: define('SCRIPT_DEBUG', true);
stackexchange-wordpress
{ "answer_score": 22, "question_score": 13, "tags": "customization, block editor" }
post created but no permalink i m trying to create a post in the custom postype via frontend , the post is created successfully too. but the cutom permalink is blank unless i go into the dashboard andclick on update $todaydate = new DateTime(); $todaydate =$todaydate->format('Y-m-d H-i-s'); $bookid="harrypotter"; $mypost= array('post_type'=>'books', 'post_title'=>$bookid, 'post_author'=>'1', 'post_status'=>'publish', 'post_date'=>$todaydate); $wpdb->insert('wp_posts',$mypost); $bookid=$wpdb->insert_id; when i go into the posttype books i find the post created but the permalink is ` instead of ` so how do i get it to update the permalink of post too
Don't insert into the database directly. Use the proper functions so that the posts are properly created before being inserted into the database. In your case the proper function is `wp_insert_post()`: wp_insert_post( array( 'post_type' => 'books', 'post_title' => 'harrypotter', 'post_status' => 'publish', 'post_author' => 1, ) ); The date field doesn't need to be set manually if you want the current time.
stackexchange-wordpress
{ "answer_score": 0, "question_score": 1, "tags": "php, theme development" }
Creating New Page with WP_INSERT_POST Issue I am trying to create a new page using the **wp_insert_post()** function as follows: $page = array('post_type' => 'page' ,'post_title' => 'The Resolution AR' ,'post_status' => 'publish' ,'post_author' => 1 ,'post_slug' => 'the-resolution-ar-2019' ); $page_id = wp_insert_post($page); A page does get created. Except, it gets created with the wrong post_slug. When I look in WP_POSTS I see the post_slug as: **the-resolution-ar** For some reason the function does not like the **-2019** portion of the slug I am providing and automatically removes it. Any ideas?
Use `post_name` instead of `post_slug` (post_slug isn't valid in `wp_insert_post`). Just make sure you don't accidentally create pages with duplicate slugs.
stackexchange-wordpress
{ "answer_score": 2, "question_score": 1, "tags": "wp insert post" }
How to update a local development plugin on a separate machine I'm developing and testing a WordPress plugin , which is working fine on my localhost. I also have a development server that mimics my current WordPress setup. When I have new changes to my plugin, and want to push these changes to my development server, can I simply re-upload my plugin zip file to see my plugin changes on my development server? Or will that cause issues?
You should try to create a git, you push from local to there and this plugin (or others, there are plenty): < Syncs the code. Good luck.
stackexchange-wordpress
{ "answer_score": 1, "question_score": 0, "tags": "plugins" }
woocommerce fail to replace template string in email title I am using Woocommerce and try to customize the emails. In the email title I've tried to use `{customer_first_name}` and `{customer_name}` with no luck. They do not get replaced. Is this a bug or are the strings I use incorrect?
The email template variables can only be used in the body of the emails. If you want to change the email titles/subject lines then you would need to use a the corresponding filter and add some custom code to a child themes functions.php file or via a custom plugin. The WooCommerce documentation has a snippet for doing this: < As an example for the processing order you would use: add_filter( 'woocommerce_email_subject_customer_processing_order', 'change_processing_email_subject', 1, 2 ); function change_processing_email_subject( $subject, $order ) { global $woocommerce; $blogname = wp_specialchars_decode(get_option('blogname'), ENT_QUOTES); $subject = sprintf( 'Hi %s, thanks for your order on %s', $order->billing_first_name, $blogname ); return $subject; } This would change the subject to: 'Hi {customer first name}, thanks for your order on {website name}'
stackexchange-wordpress
{ "answer_score": 2, "question_score": 2, "tags": "woocommerce offtopic, email" }
How would I hook into `clear_auth_cookie` to return the user's ID that's currently being logged out? `clear_auth_cookie` is what I'd need in order to catch the actual logout action, but I can't get it to return anything. < As per the Codex, it doesn't give any information. Ideally I'd like to do: add_action( 'clear_auth_cookie', 'return_user_data_on_logout'); function return_user_data_on_logout( $user ) { $id = $user->ID; //Assuming it returns a WP_User object. //Do some logic here, mostly to check if the user if is of certain type / has certain meta attached to them. } Any ideas?
That action doesn't pass that data: function return_user_data_on_logout( $user ) { Here, `$user` will alway be undefined. Additionally, you need to tell `add_action` how many parameters the function takes. But.. do_action( 'clear_auth_cookie' ); No information is passed to begin with, that's not how this particular event/action works. So how do we get the current user being logged out? The answer is we remove the words "being logged out" from that question giving us a much easier question that is far more searchable: How do we get the current user? $user = wp_get_current_user(); It's possible that this hook may be too early, and additionally it may not be the best hook to use. For example, `wp_logout` is a much better hook to use as it says on the tin what it does So: add_action( 'wp_logout', function() { $user = wp_get_current_user(); // ... });
stackexchange-wordpress
{ "answer_score": 1, "question_score": 1, "tags": "users, logout" }
child theme appears again when I put the header with parent name. My wp site suddenly showed the default theme instead of its regular child-theme. Everyhing was restored when we put the parent theme name in the header of the style.css file. But the site was running correctly without that until that moment, our style.css didn't contain that syntax. Why did it happen? It can happen again so suddenly?? tnx
Child themes will not work correctly without the parent themes folder name being in the child themes `style.css` file header as the `Template Name:` If this was missing, then someone must have removed it from the `style.css` file and it would have been in there previously if the site was working before.
stackexchange-wordpress
{ "answer_score": 1, "question_score": 0, "tags": "css, child theme, customization" }
It's not showing full content for posts pages in wordpress "[...]" while customing some changes in the style.css file I am new to wordpress.I was trying to do some changes in the style.css file but something wrong I did due to which the content for all the posts in the site it start showing "[...]" after a small content that too not in formatted form but simple.I don't know were I did wrong while customing site.And why it's showing theme name Will be very great full for any find of help![enter image description here](
The theme name is showing in the post image because, I'm guessing, you haven't uploaded a featured image for that post and it's therefore displaying a placeholder image instead. The post text (excerpt) is showing shortened due to a theme setting or how the theme intends it to look and nothing at all to do with your `style.css` file. Or, if you've customised any other theme files such as `single.php` you may have changed `the_content()` function to `the_excerpt()` which is causing the shortened text. However, as @cjbj states, you should not make changes to the parent themes CSS files or any of the other theme files. Any customisations should be done using a child theme - < It might benefit you to also read the theme documentation.
stackexchange-wordpress
{ "answer_score": 0, "question_score": -2, "tags": "php, css" }
How to know what size image to use for background? I am creating my first Wordpress site using the Sydney theme. I need to replace the background image with a different one specific to my website's purpose. I see where I can switch out the image under Appearance customization, but how can I know what the dimensions need to be?
Short Answer : Any Detailed Answer : The Sydney theme for WordPress is a very unique and responsive theme. When you upload an image for background then it will automatically be adjusted. But if you really want to add a image of specific dimensions, then 2560*1600 size is best.
stackexchange-wordpress
{ "answer_score": 2, "question_score": 0, "tags": "images" }
How to apply a function to a metadata value before launch a WP Query? I have these WP_Query arguments: $args = array( 'post_type' => 'my_post_type', 'order' => 'ASC', 'meta_key' => 'date', 'orderby' => 'meta_value_num' ); And I use `get_posts()` to call a new WP_Query($args): $posts = get_posts( $args ); Now,`date` is saved in DB like ie `2018-05-30 21:15:00`. So, I would apply a function like `strtotime('meta_value')`to convert the value in Epoch time **before** WP_Query is called and - **after** \- the posts would be filtered by Epoch time value and not by string. How can I accomplish this? Thanks!
You can't run arbitrary PHP functions in a query like that. `WP_Query` (which `get_posts()` uses) doesn't retrieve posts then filter them with PHP, it gets turned into an SQL query which finds the results. The proper way to order `meta_value` by date in SQL would be to cast it as `DATETIME`. The way `WP_Query` allows you to do this is by the `meta_type` argument. From the documentation: > You may also specify `‘meta_type‘` if you want to cast the meta value as a specific type. Possible values are ‘NUMERIC’, ‘BINARY’, ‘CHAR’, ‘DATE’, ‘DATETIME’, ‘DECIMAL’, ‘SIGNED’, ‘TIME’, ‘UNSIGNED’, same as in `‘$meta_query‘`. In your case you'd use it like this: $args = array( 'post_type' => 'my_post_type', 'meta_key' => 'date', 'meta_type' => 'DATETIME', 'orderby' => 'meta_value' 'order' => 'ASC', ); Note that I haven't tested this, as I don't have appropriate data to test with.
stackexchange-wordpress
{ "answer_score": 1, "question_score": 0, "tags": "wp query, get posts" }
Post Meta statement? I have a Post meta field in my template. I have 3 values for this meta: 1. Yes 2. No 3. N/a How can I set a custom css class according to the value ? My code: <span class="widget_last"><?php echo get_post_meta($post['ID'], 'Type', true); ?></span> Thank you
Use an `if` or `switch` statement to check the value of the meta, then echo out a different class name based on the value: <?php $type = get_post_meta($post['ID'], 'Type', true); switch ( $type ) { case 'Yes': $class = 'type-yes'; break; case 'No': $class = 'type-no'; break; default: $class = 'type-na'; break; } ?> <span class="widget_last <?php echo $class; ?>"><?php echo $type; ?></span> Now you can style each type with `.widget_last.type-yes`, `.widget_last.type-no`, or `.widget_last.type-na`.
stackexchange-wordpress
{ "answer_score": 0, "question_score": 0, "tags": "php, post meta" }
Does changing a post title of a published post automatically change permalink? In what I’ve seen and what i’ve read, changing a title to a published post won’t change the permalink. I researched again this morning and found nothing to contradict that. However, a client changed a published post’s title, several actually, and has broken links. In looking at the editor, the permalink had in fact changed. I fixed it by editing the permalink back to the original, keeping the updated title. Site uses Divi and Yoast, if that’s relevant. What is the truth here? Thanks.
Just tested it. Looks like the client also changed the permalink. Remember when you click on "Edit" in the permalink and write some text and then click OK Wordpress will convert that link into a permalink. ![enter image description here]( ![enter image description here](
stackexchange-wordpress
{ "answer_score": 1, "question_score": 1, "tags": "permalinks, url rewriting, title" }
Limit amount of categories displayed in a post I'm trying to limit the amount of categories that show up above my post title, below is an example of what is happening ![enter image description here]( I'm fine with just grabbing the first 2 categories that show up and limit them to that. I have found functions that accomplish this with tags but nothing with categories. For example in this custom function, it limits the tags to five in `functions.php` add_filter('term_links-post_tag','limit_to_five_tags'); function limit_to_five_tags($terms) { return array_slice($terms,0,5,true); } Then in `single.php` use `<?php the_tags() ?>`. Any idea how to accomplish this with categories?
In your functions.php, you can filter `the_category_list`, which is an array of categories for a post. function wpse_the_category_list( $categories, $post_id ) { return array_slice( $categories, 0, 2, true ); } add_filter( 'the_category_list', 'wpse_the_category_list', 10, 2 ); And then display the categories in your template file with: the_category();
stackexchange-wordpress
{ "answer_score": 0, "question_score": 0, "tags": "posts, categories" }
Add custom <li>-element to wp_nav_menu How can I add a custom < li>-element to wp_nav_menu()? My menu includes already all my categories, but it should also include a < li>-element that contains a search form. From header.php <nav> <?php $args = array( 'theme_location' => 'nav_main' ); wp_nav_menu($args); ?> <?php get_search_form(); ?> </nav> \--Edit-- This is how it looks now: ![enter image description here]( This is how it should look: ![enter image description here](
The `wp_nav_menu()` function has an `items_wrap` parameter which contains this by default: <ul id="%1$s" class="%2$s">%3$s</ul> So you can pass it the above default plus any appended string: $search_form = get_search_form( false ); // Return not echo $items_wrap = '<ul id="%1$s" class="%2$s">%3$s'; $items_wrap .= sprintf( '<li id="searchItem">%1$s</li></ul>', $search_form ); wp_nav_menu( array( 'items_wrap' => $items_wrap, ) );
stackexchange-wordpress
{ "answer_score": 4, "question_score": 1, "tags": "menus" }
Using wp_insert_post and post_update_meta but need to fire save_post afterward I am using a calendar plugin. I have been using form data to create a new custom post type of calendar plugin and then update post meta custom fields for that calendar plugin. This works. However there are other post meta that fired upon save_post action from the plugin classes. I am trying to find a way to fire: do_action( 'save_post', $post_id, $post, $update ); afterward. I have the $post_id but not the $post or $update. so that it fires all the methods as if I am clicking on save post in the admin. Thank you,
You should be able to use `wp_update_post()` -< Eg. $my_post = array( 'ID' => $post_id, ); wp_update_post( $my_post ); The 'save_post' action should run when this function is called.
stackexchange-wordpress
{ "answer_score": 2, "question_score": 3, "tags": "actions" }
Is it possible to determine whether a page is a page template by page_id in ajax call? I'm looking for an answer for the asked question. The reason is I'd like to omit the need to use is_page_template() in WP ajax calls. Best regards, Dan.
To get the page template of an arbitrary page by ID you can use `get_page_template_slug()`: // Set $page_id somehow, probably getting it from AJAX request. $template = get_page_template_slug( $page_id ); if ( $template === 'templates/about.php' ) { // Do something. }
stackexchange-wordpress
{ "answer_score": 1, "question_score": 0, "tags": "ajax, page template" }
wp_head() outputs in body I've got a simple header file which calls the wp_head method, however when i inspect the source the css links are made in the body and the `<head>` is empty. My header.php: <!DOCTYPE html> <html lang="en"> <head> <?php wp_head(); ?> </head> <body> <?php get_template_part( 'components/navigation/navigation', 'main' ); ?> My functions.php: <?php function load_scripts() { echo ' test'; wp_enqueue_style( 'style', get_stylesheet_uri() ); } add_action('wp_enqueue_scripts', 'load_scripts'); ?> Thanks!
This is your browser's attempt to avoid invalid markup. Your `echo ' test';` outputs something that does not belong in a `head` tag, so the browser closes it and opens the `body` tag. If you look at the actual unprocessed response from the server, it won't appear this way, but that `echo` shouldn't be there regardless, and this issue will disappear when you remove it.
stackexchange-wordpress
{ "answer_score": 5, "question_score": 3, "tags": "wp head" }
How to access "default" property of attribute in Gutenberg In a Gutenberg block I try to read the value of an attribute's _default_ property, so that I can find out in the transformation routine (to another block type) if any give attribute still has the default value. With `this.props.attributes` I only see the _values_ of attributes, but I need their "meta data". One sample declaration in **registerBlockType** would look like: attributes: { amount: { type: 'integer', default: 1 }, // ... }
I just found out that I can simply define a variable when I register the block var myBlock = registerBlockType( ... ) and then inside the anonymous function for "transform" I can access the attributes as myBlock.attributes
stackexchange-wordpress
{ "answer_score": 0, "question_score": 3, "tags": "block editor" }
Dynamic_sidebar load in string makeup In my Wordpress theme the header is loaded through a string example below, i wish to be able to load a dynamic sidebar (widget) in it but its not working and only showing on front-end the number '1' where it should be loaded. can anyone help with how to load a sidebar in the string makeup? `$menu_markup = '<header class="%s header"> '. dynamic_sidebar('header-widget').' </div>`
You could use output buffering to catch the display of the sidebar. This does make it a bit more difficult to debug should you need to but it will get you what you need: ob_start(); dynamic_sidebar( 'header-widget' ); $sidebar = ob_get_clean(); $menu_markup = '<header class="%s header">' . $sidebar . '</div>';
stackexchange-wordpress
{ "answer_score": 0, "question_score": 0, "tags": "php, widgets" }
Exclude child pages from archive.php I've created a hierarchical custom post type called "Services". Here are the pages I've added within the custom post type: * Service 1 * Service Child (Service 1 is Parent) * Service Child (Service 1 is Parent) * Service 2 * Service Child (Service 2 is Parent) * Service Child (Service 2 is Parent) * Service 3 * Service Child (Service 3 is Parent) * Service Child (Service 3 is Parent) * Service 4 * Service Child (Service 4 is Parent) * Service Child (Service 4 is Parent) Is it possible to exclude the child pages from archive-services.php? I was hoping to achieve this using pre_get_posts, but it doesn't seem possible.
Of course it is possible. All you have to do is to set `post_parent` argument to `0`. function remove_children_from_archive( $query ) { if ( ! is_admin() && $query->is_main_query() && is_post_type_archive('my_custom_post_type') ) { // of course you'll have to change my_custom_post_type to real slug - probably services $query->set( 'post_parent', 0 ); } } add_action( 'pre_get_posts', 'remove_children_from_archive' );
stackexchange-wordpress
{ "answer_score": 2, "question_score": 1, "tags": "custom post types, posts" }
How to get the Page Number of the Current Page in Single Post Pagination Let's say I have "Single Post" that is split by `<!--nextpage-->` pagination. And there are total of 50 Pages. So a user is browsing on that post and he is at page 25. I want the Post to Display which Page he is at. So it just shows **Page Number : 25** If the question isn't clear you can comment requesting for more details and I will edit the question to elaborate it even more. But I guess it's not that hard to interpret this question. Thanks for Helping out!
For your single page, you could try using the global `$page` variable. Another alternative would be to try fetching the query `page` variable, with e.g.: $wpse_current_page = (int) get_query_var( 'page' ); if( $wpse_current_page > 0 ) { printf( __( 'Page Number: %d', 'wpse-theme-slug' ), (int) $wpse_current_page ); } on your single page.
stackexchange-wordpress
{ "answer_score": 2, "question_score": 1, "tags": "php, pagination" }
Force pretty permalinks? I'm building a plugin that will be used for a single site and relies on `add_rewrite_rule` to work, which requires permalinks to be turned on. It's no trouble to turn them on since it's only a single site, but I'm concerned that one of the admins may turn it off not realizing what they're doing and break the site. How can I programmatically force pretty permalinks to remain on?
Not exactly the solution you're asking for, but here's how I would deal with such problem... If your plugin needs permalinks to be turned on, then I would put some checks and display a notice, if they're not turned on. I don't think that plugin should force anything. There can be a lot of reasons that somebody turned permalinks off (for example they were breaking the site).So if your plugin will force them, then dealing with such problem would be very hard. And to be honest - it will be really hard to find why permalinks aren't turning off. On the other hand... If I turn permalinks off and there will be notice, that your plugin may not work properly, everything will be clear and everyone will remember, why this plugin isn't working. It's much nicer approach, I guess. So the last part is the check itself. So how to check if permalinks are enabled? Codex tells you how: if ( get_option('permalink_structure') ) { echo 'permalinks enabled'; }
stackexchange-wordpress
{ "answer_score": 1, "question_score": 1, "tags": "permalinks" }
WordPress custom CSS file overrided by internal CSS I have started to convert my static page to WordPress theme. While I am doing this I have a place where the position of the background image of a section has to be set with values like `background-position:0 80%;`. When I add the CSS to my custom CSS file which is main.css I found out there an internal CSS which is overriding my CSS like `background-postion:center !important`. Then I changed my CSS to `background-position:0 80%; !important` But it still doesn't work and I found out my CSS file is included before the internal CSS in the head ( **by view page source code** ). Now what I want to know is how can I change the order or how can I import my custom CSS ( **main.css** ) file after the internal CSS code?
First of all it should be: `background-position:0 80% !important;` You said this style is applied to sections. How? If you just add another selector, like instead using: article{ background-position:0 80% !important; } use: body article{ background-position:0 80% !important; } it may just work without any hacks.
stackexchange-wordpress
{ "answer_score": 1, "question_score": 0, "tags": "css" }
Wordpress updates and Git How to handle wordpress core and plugin updates when using git? I need to update my core and plugins. I have site on my localhost and live site on server. If I update localy and then commit+push changes it breaks site because the live database is not updated. If I update live site I have no changes on localhost, and no way to test if update breaks site.
In my readings (and as mentioned in OP comments) the best practice seemed to be focusing on the `/wp-content/` folder, or specific custom contents therein. Syncing all the core files and third party plugins just causes headaches and unnecessary version monitoring. I had troubles with this myself, but it's best to remove the mentality that repo act as a mirrored / complete backup, because (from reading & my own experience, as well as your post shows), it doesn't work well that way. If it's just a handful of themes/plugins < is an incredible tool to handle the deployment from git to production. This old post stevegrunwell.github.io/wordpress-git/ is a good resource for defining the line between what to include and exclude for the local/git/live workflow. Most notably, slide 13 shares and awesome `.htaccess` rewrite to use remote media files so you're not always keeping local in sync.
stackexchange-wordpress
{ "answer_score": 2, "question_score": 1, "tags": "automatic updates, git" }
Query Column of Specific ID from Database Table I am trying to display a particular value from the WordPress database for a specific ID with no such luck. I am not receiving any errors, but just an empty result. Here is my table: table name: _customtable id item_key item_value 1 url 2 techurl Here is the code I'm trying to use to display the techurl value in item_value global $wpdb; $table_name = $wpdb->_customtable; $retrieve_data = $wpdb->get_results( "SELECT * FROM $table_name WHERE 'id'= 2" ); foreach ($retrieve_data as $retrieved_data) { echo $retrieved_data->item_value; }
You have 2 two problems here: \- You can't use $wpdb-> with custom tables because [postmeta, posts, ...] are variables in the class $wpdb. \- WHERE 'id'= 2 is not correct WHERE id = 2 So it should work: global $wpdb; $table_name = "_customtable"; $retrieve_data = $wpdb->get_results( "SELECT * FROM $table_name WHERE id = 2" ); foreach ($retrieve_data as $retrieved_data) { echo $retrieved_data->item_value; } Regards.
stackexchange-wordpress
{ "answer_score": 1, "question_score": 0, "tags": "database, query, mysql, wpdb" }
Add To Gutenberg Sidebar I'm trying to make sense of how to add custom page options to the right side of the Gutenberg interface. I don't _think_ need a content block, I just need to be able to add a page-specific configuration, but can't seem to make it work correctly. Pre-Gutenberg I would resolve this with a metabox placed in the right side, however, from what I'm reading it sounds like metaboxes are going to be a bad practice moving forward.
If you're looking to work with the Gutenberg sidebar, WordPress has a provided tutorial that will teach you exactly how to do this: <
stackexchange-wordpress
{ "answer_score": 1, "question_score": 9, "tags": "block editor" }
How do I fully rid of the 1px wide sidebar border? < Arrow pointing to border in this screenshot: < On the above page, I tried many CSS tricks, but I can't fully get rid of this 1px border between sidebar and main content. It is very faint, but if you look closely it's there.
It looks like your in themes style.css at a certain breakpoint `min-width: 769px` it's adding a border right. You could get rid of it by adding the following to your child themes CSS or The Customizers CSS Panel: @media (min-width: 769px) { .ast-right-sidebar #primary { border-right: 0px; } }
stackexchange-wordpress
{ "answer_score": 0, "question_score": 0, "tags": "sidebar" }
how to send email to administrator when someone edit post I made custom-post-type(book). And in my site, anyone can register and write book(custom-post-type) and also edit this book post-type. And I want to get email-alarm when someone edit their book post-type. Is there some ways to code like this without plugin? Thank you.
Here in Wordpress.org you have a example to do that: < Look also here to see when it modified < Regards.
stackexchange-wordpress
{ "answer_score": 1, "question_score": 0, "tags": "custom post types" }
Highlight the first page pagination_links i need help in WordPress. I'm not a WordPress developer, but for some reason i have to change some code in here. Now coming to the point. I have a page where i'm showing some content with pagination. Im using `paginate_links()` to generate the pagination. When i'm in the first page, page number not highlighting it. But from 2nd page its highlighting the page number. But i also want to highlight the first. Here is my code i used: <?php $args = array( 'base' => '%_%', 'format' => '#page%#%', 'total' => $sitesQuery->max_num_pages, 'current' => $page, 'show_all' => false, 'prev_next' => true, 'end_size' => 2 ); echo paginate_links($args); Can anyone help me out with this?
Are you looking for something like this? ![Second Page Selected]( You need to add style for the class .current also current page number wrapper in span you can also use this to style. ![Current Page Selected]( ![enter image description here]( <span class="page-numbers current">1</span> <a class="page-numbers" href="#page2">2</a> <a class="next page-numbers" href="#page2">Next »</a> When you go to page 2 structure become <a class="prev page-numbers" href="">« Previous</a> <a class="page-numbers" href="">1</a> <span class="page-numbers current">2</span> Tested your code its working fine all you need to do is add style for it. .current{ background:yellow; padding:10px; }
stackexchange-wordpress
{ "answer_score": 1, "question_score": 0, "tags": "paginate links" }
Issue with TABLE or DIV padding on Mobile I have an issue on a page when viewed on a mobile device. This page (since issue has been solved this page won't be accessible any longer), when viewed on a browser looks perfect. But when I view it on my mobile device (iPhone using latest Chrome app version) the page looks broken on the right margin (as per the screenshot below). If I decrease the cell padding values it works, but it depends on the mobile screen size. The smaller the screen the less padding I can have. If I remove the cell padding it seems to work on all screen sizes. Any help would be greatly appreciated! ![](
This is a common CSS problem. In your table, there are too many columns for the width to accommodate, so div.table is overflowing from its container. To fix, wrap div.table inside another div. Set the outer div to: width:100%; overflow:auto; div.table will now stay within the boundaries without breaking the right margin, but will need to be side-scrolled to be fully viewed.
stackexchange-wordpress
{ "answer_score": 0, "question_score": -1, "tags": "css" }
phpcs error in WordPress I'm working with the MegaMenu here `echo wp_nonce_url()` is showing an error `All output should run through an escaping function` according to wpcs. I gave `echo esc_url( wp_nonce_url())` Is it correct? Point me where am I going wrong. ![enter image description here](
Yes it is correct. Escaping should be done based on context, and since `wp_nonce_url()` is used in an `href`as proper url, you should use `esc_url`.
stackexchange-wordpress
{ "answer_score": 1, "question_score": 0, "tags": "nonce" }
Wordpress and Woocommerce Chinese Permalink So I've been working on this ecommerce site but I've problem with chinese character permalink. For example `localhost/product-category/` will render 404, as it will completely substitute the chinese character to question mark, like so `localhost/product-category/?/` . Same goes to `/localhost/archives/category/...` I'm looking for a way to make it work, but not by translating it to pinyin or english/latin. Any .htaccess/web.config(It's running under IIS) approach or it's technically not possible? Or do I need plugins like WPML (it's english website but having products with chinese character). Couldn't find any working solution, just yet.
Turns out this was caused by IIS. If you already have `<action type="Rewrite" url="index.php" />` in your web.config, that should be enough with this addition to your `index.php` in the Wordpress root installation directory `if (isset($_SERVER['UNENCODED_URL'])) { $_SERVER['REQUEST_URI'] = $_SERVER['UNENCODED_URL']; }` The php code is quite self explanatory.
stackexchange-wordpress
{ "answer_score": 0, "question_score": 0, "tags": "permalinks, woocommerce offtopic" }
back up fully Customized WordPress theme How to back up fully Customized WordPress theme and its page, post, full setting, contact form 7 data? So that we can install it directly on any other WordPress website.
Best practice to backup whole theme and data, first you need to export the XML file. Login to WordPress Dashboard > Tools > Export ![export-xml]( Every theme save their options differently, You can use third party plugin which favors your theme to export the settings.
stackexchange-wordpress
{ "answer_score": 0, "question_score": 0, "tags": "backup" }
Gravity Forms, multiple conditions in shortcode Gravity forms offers a shortcode for conditional display based on responses. > [gravityforms action="conditional" merge_tag="{:3}" condition="less_than" value="30"] Your value is less than 30 [/gravityforms] Is there a way to use TWO conditions in this shortcode? For example, I need to do greater than 10 and less than 30, like: > [gravityforms action="conditional" merge_tag="{:3}" condition="greater_than, less_than" value="10,30" ] Your value is greater than 10 and less than 30 [/gravityforms] The above doesn't work, but wondering if anyone has found a way to do this?
You can nest the singular and plural versions of the shortcode: `[gravityforms action="conditional" merge_tag="{:3}" condition="greater_than" value="10"] [gravityform action="conditional" merge_tag="{:3}" condition="less_than" value="30"]Your value is greater than 10 less than 30[/gravityforms] [/gravityforms]` More details on that here: < \- OR - You can use this snippet to create multiple conditions in a single shortcode: < `[gravityforms action="conditional" relation="and" value="{:3}" operator="greater_than" compare="10" value2="{:3}" operator2="less_than" compare2="30"] Your value is greater than 10 less than 30 [/gravityforms]`
stackexchange-wordpress
{ "answer_score": 1, "question_score": 0, "tags": "conditional tags, plugin gravity forms" }
Shortcode to show the code how can I create a shortcode (or something similar) to show the footer in somewhere on a page? I tried with this but no results... function show_footer() { return get_footer(); } add_shortcode( 'show_f', 'show_footer' ); or this... function show_footer() { get_footer(); } add_shortcode( 'show_f', 'show_footer' ); any idea? many thanks
`get_footer()` echos the contents of the footer.php file. `add_shortcode()` requires that the callback return the contents of the shortcode and not echo it. I suppose you could do something like this if you really want. function show_footer() { ob_start(); get_footer(); return ob_get_clean(); } add_shortcode( 'show_f', 'show_footer' );
stackexchange-wordpress
{ "answer_score": 6, "question_score": 0, "tags": "php, shortcode" }
WPDB prepare - like % - placeholders? Are these `{xxx...}` placeholders for `%` in a LIKE statement normal? If so, when do they get converted back to `%`'s? SHELL wp> global $wpdb; wp> $q = "%s"; => string(2) "%s" wp> $pq = $wpdb->prepare($q, '%hi%'); => string(136) "'{6e039dc0b074a5ff6828a070d0c24708d132341f32dff55a053f1410beabaacd}hi{6e039dc0b074a5ff6828a070d0c24708d132341f32dff55a053f1410beabaacd}'"
Yes, they're normal. They were added in 4.8.3 to fix an SQL injection vulnerability. You can read an article describing the technical reasons for this happening here and the ticket for the change here. The placeholder characters are replaced by the random characters on the last line of `$wpdb->prepare()` with the `$wpdb->add_placeholder_escape()` function, which calls `$wpdb->placeholder_escape()` internally. These placeholders are removed in `$wpdb->query()` by the `$wpdb->remove_placeholder_escape()` function which is added as a filter to the `query` hook.
stackexchange-wordpress
{ "answer_score": 13, "question_score": 10, "tags": "wpdb" }
Changing the HTML Of the content <?php the_content(); ?> When we use the above the content is published like this → <p>Content is published</p> If I want to later this HTML and instead of `<p></p>` I want that `<h3></h3>` should be there. Is that possible?
The wrapping `<p>` is applied by a filter called `wpautop`. You can disable this filter and wrap the content in your desired wrapper, but it's not really recommended. remove_filter( 'the_content', 'wpautop' ); remove_filter( 'the_excerpt', 'wpautop' ); Now you can wrap your content in a DIV for example: <div><?php the_content(); ?></div> But notice that this filter is applied to more than just beginning and the end. It's applied to paragraphs and galleries, etc. Disabling it might not have the desired effect.
stackexchange-wordpress
{ "answer_score": 4, "question_score": 1, "tags": "php, functions, the content" }
Dilemma of Populating all the categories in a drop down list A general drop down list with some generic HTML will go down like this → <select> <option value="volvo">Volvo</option> <option value="saab">Saab</option> <option value="mercedes">Mercedes</option> <option value="audi">Audi</option> </select> But what If we wish to populate all the categories in this drop down? what will we write in the `value=""` section so that we get the unique Value property. Apart from that, I think that the loop will run such as for $categories as $categorie It is more of a PHP question I think and less of a WordPress. Can someone help me in taking things further?
WordPress has a specific function to do what you want, `wp_dropdown_categories`. By default it will fill the value field of the option with the term id, which would be unique, but there are several other options to choose from, which you can pass as an argument when calling the function. If that doesn't satisfy you, you can even make a walker function, which changes the dropdown function completely. An example is found at the bottom of the first link. So, you can do this with one line in your template file or make it as complex as you might desire.
stackexchange-wordpress
{ "answer_score": 3, "question_score": 0, "tags": "php, functions, categories" }
Easy WP SMTP plugin test email failed I'm new to the Wordpress world and just installed the `Easy WP SMTP` plugin on the website. At the time of sending the test email, I get an error message. The debug info says, Debug Info CLIENT -> SERVER: EHLO localhost SMTP Error: Could not authenticate.CLIENT -> SERVER: QUIT SMTP connect() failed. I added the setting here. ![enter image description here]( Anyone know what is the issue here?
If you want to configure Gmail account, you need to fill Encryption type: SSL Port: 465 Requires Authentication: Yes Or you can try < This would help you in authenticating the Gmail account using oAuth.
stackexchange-wordpress
{ "answer_score": 1, "question_score": 0, "tags": "plugins, smtp" }
If user has 1 post then dont let him create new one I have tryied all plugins. I need a php code not a plugin cause im running a front end post creator. I need a function or a php code which only allows a user to have 1 post only but if that post is deleted he can then make a new post.
You can use count_user_posts function. If the posts are getting saved as WordPress posts then it can be done by the snippet below: if (is_user_logged_in()){ $userPostCount = count_user_posts(get_current_user_id()); if ($userPostCount > 1){ $user = new WP_User(get_current_user_id()); $user->add_cap('publish_posts',false); } else { $user->add_cap('publish_posts',true); } }
stackexchange-wordpress
{ "answer_score": 0, "question_score": 0, "tags": "posts, limit" }
Attaching an upload to a user Is there any way with WordPress that a user could upload a file (pdf or jpg, for example) and have that image 'attached' to their account? Ultimately, I'd like to be able to have a Gravity Forms form that automatically populates the user's name, contact info and this file, kind of like a job site where you can send all your info and your uploaded resume with one click.
you can create a single page that doesn't let them register and then asking their First Name, Last Name and other details. ![enter image description here]( And then use the field upload in the advance fields ![enter image description here]( on the backend view you will be able to see the submission together with their name, address and other details and the file they included in their attachment. ![enter image description here](
stackexchange-wordpress
{ "answer_score": 0, "question_score": 0, "tags": "php, media, user registration, plugin gravity forms" }
Gutenberg extend blocks add new class name I'm trying to add an extra class name to all the blocks by extending them. Documentation: Extending Blocks I'm using `blocks.BlockEdit` to modify the edit component. I want to add a custom class name. So far I have this const withClass = createHigherOrderComponent( ( BlockListBlock ) => { return ( props ) => { let wrapperProps = props.wrapperProps; wrapperProps = { ...wrapperProps, className: 'my-custom-class', }; return <BlockListBlock { ...props } wrapperProps={ wrapperProps } />; }; }, 'withClass' ); It's working by adding the custom class to the wrapper but it is overwriting the default block class. Is it possible to append to the current classes without overriding?
Yes, you can do this via the `classnames()` function. import classnames from 'classnames'; const withClass = createHigherOrderComponent( ( BlockListBlock ) => { return ( props ) => { let wrapperProps = props.wrapperProps; wrapperProps = { ...wrapperProps, className={ classnames( 'my-custom-class', props.className ) } }; return <BlockListBlock { ...props } wrapperProps={ wrapperProps } />; }; }, 'withClass' );
stackexchange-wordpress
{ "answer_score": 4, "question_score": 3, "tags": "javascript, block editor" }
post__in not recognizing multiple IDs I have a bit of an issue regarding post__in When I do: $newstring = '15,30'; $args = array( 'post__in' => array($newstring) ); $loop = new wp_query($args); It only displays the first post (id=15) But when I do: $args = array( 'post__in' => array(15,30) ); $loop = new wp_query($args); It works as it should. The post IDs though is set somewhere. How do I solve this one using the first scenario? Thanks.
This is more of a PHP than a WordPress issue: If `$newstring = '15,30';` then `array($newstring)` is an array containing this string. If you `print_r( array($newstring) )`, it looks like this: Array ( [0] => 15,30 ) Which is not the same as `array(15,30)`. What you want to do instead is: $newstring = '15,30'; $args = array( 'post__in' => explode(',', $newstring) ); `print_r( explode(',', $newstring) )` will look like: Array ( [0] => 15 [1] => 30 ) Which now is exactly the same as `array(15,30)`. See `explode()` to better understand how this function works.
stackexchange-wordpress
{ "answer_score": 2, "question_score": -1, "tags": "wp query" }
Replace Vimeo and Youtube in from scratch theme with from-the-group-up single post template? I've inherited a theme that uses a totally in-house post display, and doesn't use the post loop. My question is, what function do I have to feed my post content object through in order to use oEmbed to replace the YouTube and Vimeo links in the post body with the oEmbed code?
You might be looking for `WP_Embed::autoembed()`. Try: add_filter( 'the_content', array( 'WP_Embed', 'autoembed' ) ); in your theme's `functions.php` file.
stackexchange-wordpress
{ "answer_score": 0, "question_score": 0, "tags": "customization, oembed" }
Using get_post_type with a custom URL format? I have a custom post type with rewritten URLs. Slug is: top-news Rewrite is: top/news I have a function that updates the last modified date whenever a comment is posted that works correctly (found here), however I want this to apply only to this custom post type. I tried wrapping the function in: if ( is_singular( 'top-news' ) ) { } and also with: if( get_post_type() == 'top-news' ) { } However these don't seem to work, any help would be greatly appreciated.
If you're doing something in the `wp_insert_comment` hook, then you should use the 2nd argument, `$comment_object`, if you want to know anything about the post the comment was for. `$comment_object` is a `WP_Comment` object that has a `$comment_post_ID` property that has the ID of the post the comments is for. You can use that to determine its post type. The URL structure is completely irrelevant. function wpse_304105_update_time( $comment_id, $comment_object ) { $post_id = $comment_object->comment_post_ID; if ( get_post_type( $post_id ) === 'top-news' ) { // Update post time. } } add_action( 'wp_insert_comment', 'wpse_304105_update_time', 99, 2 );
stackexchange-wordpress
{ "answer_score": 0, "question_score": 0, "tags": "custom post types, functions, url rewriting" }
ACF Pro make URL Linked in Custom Template I am new to ACF and Custom Post Types and novice at best with PHP & Coding. I need help to make `the_field` linked on my front end display. I also want to show the link as the link text. <?php if( get_field('svcta_contact_information_group_svcta_contact_website')) { echo '<div class="svcta-contact-website" id="svcta-id-contact-website">'; echo '<strong>Contact Website:</strong> '; the_field('svcta_contact_information_group_svcta_contact_website'); echo '</div>'; } ?> Thanks for the help.
You echo value of the field, so you get what you do ;) There is no way to make ACF print it your way. You have to wrap it yourself. Here's a code that would do exactly that: <?php if ( get_field('svcta_contact_information_group_svcta_contact_website') ) : ?> <div class="svcta-contact-website" id="svcta-id-contact-website"> <strong>Contact Website:</strong> <a href="<?php echo esc_attr( get_field('svcta_contact_information_group_svcta_contact_website') ); ?>">Link Caption</a> </div> <?php endif; ?>
stackexchange-wordpress
{ "answer_score": 1, "question_score": 0, "tags": "theme development, urls, advanced custom fields" }
Create Custom Post Type Permalink Structure Is there an easy way to have a permalink structure for Custom Post types that looks like this? `mysite.com/post-type/` \- Listing Page for Post Type `mysite.com/post-type/taxonomy/` \- Category/Taxonomy Listing Page `mysite.com/post-type/post-name/` \- Single Page for Post Type I have tried the plugin WP Better Permalinks, but it adds a taxonomy to the URL when viewing the single page, which I do not want at all. Similarly, the inbuilt WordPress permalinks add 'categories', or the name of your custom taxonomy to the URL. Again, not what I want.
The default behaviour of `mysite.com/post-type/` and `mysite.com/post-type/post-name/` is what you want it to be, so you don't need to do anything special there. To have `mysite.com/post-type/taxonomy/` as the URL for the taxonomy archive, all you need to do is use `'post-type/taxonomy'` as the `rewrite => slug` argument when registering the taxonomy.
stackexchange-wordpress
{ "answer_score": 2, "question_score": 1, "tags": "custom post types, taxonomy" }
Open "Visit site" in a new window? I have managed to make the admin bar "Visit site" to open in a new window. But in a multisite setup there is a menu item called "My sites" which displays all your sites with a link to "Dashboard" and "Visit site". How do I make this "Visit site" button open in a new link? Thank you! EDIT: Here is the solution for the drop-down menu "My sites": add_action( 'admin_bar_menu', 'remove_nodes_mysites', 999 ); function remove_nodes_mysites( $bar ) { $sites = get_blogs_of_user( get_current_user_id() ); foreach ( $sites as $site ) { // Open Visit Site in new window/tab $visit_site_node = $bar->get_node( "blog-{$site->userblog_id}-v" ); // Visit Site $visit_site_node->meta['target'] = '_blank'; $bar->add_node($visit_site_node); } }
This should do it (put it in a network activated plugin): add_filter( 'myblogs_blog_actions', 'my_sites_visit_site_target_blank', 10, 2 ); function my_sites_visit_site_target_blank( $actions, $user_blog ) { $to_replace = ">" . __( 'Visit' ) . '</a>'; $to_replace_with = " target='_blank' >" . __( 'Visit' ) . '</a>'; return str_replace( $to_replace, $to_replace_with, $actions ); }
stackexchange-wordpress
{ "answer_score": 1, "question_score": 0, "tags": "customization, multisite" }
customize the body of the autoresponder email I have to customize the body of the autoresponder email in Contact Form 7. As I have one dropdown on the form, on the basis of dropdown I have to update the autoresponder content in the mail. For the main email I am doing like this $mail = $contact_form->prop( 'mail' ); $mail['body']= "CUSTOM BODY TEXT"; $contact_form->set_properties( array( 'mail' => $mail ) ); Please tell me how to update the auto responder mail
Just use mail_2 instead of mail $mail = $contact_form->prop( 'mail_2' ); $mail['body']= "CUSTOM BODY TEXT"; $contact_form->set_properties( array( 'mail_2' => $mail ) );
stackexchange-wordpress
{ "answer_score": 2, "question_score": 0, "tags": "plugin contact form 7" }
Get Data From wp_sitemeta for Multisite network I have a multisite network with around 30 sites on it. In the `wp_sitemeta` table, there are some options the previous dev had set (one of which is 'template_color'). So in the `wp_sitemeta` table, there is a `site_id` with a `meta_key` of 'template_color', and a `meta_value` of the hex value of the color. I've written the following: foreach ( $sites as $site ) { switch_to_blog( $site->blog_id ); //do things $value = get_site_option( 'template_color', 'not available' ); echo $value; restore_current_blog(); } But `$value` just shows 'not available' for each site. Am I doing something incorrectly?
The documentation for this is contradictory, but I believe wp_sitemeta is meant to only store information for sites in the wp_sites table, which only stores the main site in a network. It would make more sense to store each site's template_color in their individual wp_[BLOGID]_options tables. However, keeping the data as-is, you may be able to use the following instead of get_site_option: get_network_option( $site->blog_id, 'template_color', 'not_available' )
stackexchange-wordpress
{ "answer_score": 3, "question_score": 0, "tags": "custom field, multisite, meta query, options" }
Change order/position of Gutenberg inspector control panel I'm adding a new panel to a Gutenberg block through the `editor.BlockEdit` wp.block filter. <InspectorControls> <PanelBody title={ __( 'New Settings' ) } initialOpen={ false } > ... </PanelBody> </InspectorControls> The new panel appears on top of the default panels. Is there any way to change the order? To make it show below other panels? I did not find any documentation about this..
<InspectorControls> <PanelBody title={ __( 'Settings One' ) }> </PanelBody> <PanelBody title={ __( 'Settings Two' ) }> </PanelBody> <PanelBody title={ __( 'Settings Three' ) > </PanelBody> </InspectorControls> If you insert multiple Panelbody like I did in above code. You will have multiple inspector controls with first one being ope by default. Change the panelbody accordingly to match your desired order.
stackexchange-wordpress
{ "answer_score": -4, "question_score": 7, "tags": "block editor" }
Is the first item returned by get_posts() always the latest post? I want to retrieve the modification date of the latest post. To do this, first I get the latest post: $latest_post = get_posts()[0]; Can I be certain that the returned object is always the latest post or are there circumstances where the order of objects returned by `get_posts()` is different?
Yes and Maybe Yes: According to < the default is ordered by date in a descending order. Maybe: But plugins may change the query through ie hook(s) **pre_get_posts**. * < * <
stackexchange-wordpress
{ "answer_score": 6, "question_score": 5, "tags": "php, get posts" }
If specific user role then sticky post We say if a user has user role author then all his new posts will automaticly be sticky. How can i do that?
add_action('save_post', 'mo_make_it_sticky_if_role'); function mo_make_it_sticky_if_role( $post_id ) { if( current_user_can('author') ) { stick_post( $post_id ); } } If the user has user role _author_ and he creates a new post then it gets sticky as default even if he uses somecind of fron-end post creator. It will only work if the _author_ makes a new post. His old posts which he created before this function was added will not get sticky.
stackexchange-wordpress
{ "answer_score": 0, "question_score": 2, "tags": "posts, wp query, filters, user roles" }
Force category choice before creating new post I see this post < Code it working, but i want change category = my custom taxonomy "chuyen-muc", someone help me, thanks.
Use the 'save_post' hook to programmatically enteract with your new post when it is created, then use the `wp_set_post_terms()` function to assign your term, add_action('save_post','set_post_default_category', 10,3); function set_post_default_category($post_id, $post, $update){ if($update) return; //only want to set if this is a new post! if('post' !== $post->post_type) return; //only set for post_type = post! $term = get_term_by('slug', 'my-custom-term', 'category');//get the default term using the slug, its more portable! wp_set_post_terms( $post_id, $term->term_id, 'category', true ); }
stackexchange-wordpress
{ "answer_score": 1, "question_score": 0, "tags": "categories, post editor" }
how to edit woocommerce checkout page i have created my own theme for my woocommerce store i'm facing a layout issue in the checkout page, after debugging in chrome tools somehow i find out that the default main div is set to col-1 and if i were to edit it to col-12 that would fix the issue here however i'm using shortcode to use the woocommerce checkout functionality so i dont really have checkout page file and so not able to edit/override the checkout page so please if anyone can help me on how to set the default div from col-1 to be col-12 would be much appreciable. Thanks. ![enter image description here](
this solves the issue here: .woocommerce .col-1, .woocommerce .col-2 { max-width:none; }
stackexchange-wordpress
{ "answer_score": 0, "question_score": 0, "tags": "theme development, customization, woocommerce offtopic, shortcode" }
next comment id number wordpress I have removed many spam comments from my very old blog (over 3500 spam comments) and purged from the database. Last comment ID was 3620 after removal latest comment has ID 853. New added comment should now have ID: 854 but it has ID: 3621. Is it possible to change it and reuse old IDs ? I looked in wp_options table but I have not found any settings associated with it. Where is it saved in the database? How to change it.
Backup your comments table first. If you're only dealing with comments marked as spam by Akismet, Akismet sets a WordPress cron to clean up the comment meta table so you don't have to worry about that table. Check this answer on StackOverflow I would go into PHPMyAdmin, select the comments table and run this query: ALTER TABLE your_comments_table_name AUTO_INCREMENT = 854
stackexchange-wordpress
{ "answer_score": 0, "question_score": 0, "tags": "database, mysql" }
How to implement color picker from wordpress in my plugin? I'm having difficulty implementing the color picker exactly the same as WordPress in my plugin. Is there any official wordpress documentation on how to use this feature?
Yes, there is: < ## 1\. You should enqueue scripts and styles... add_action( 'admin_enqueue_scripts', 'mw_enqueue_color_picker' ); function mw_enqueue_color_picker( $hook_suffix ) { // first check that $hook_suffix is appropriate for your admin page wp_enqueue_style( 'wp-color-picker' ); wp_enqueue_script( 'my-script-handle', plugins_url('my-script.js', __FILE__ ), array( 'wp-color-picker' ), false, true ); } ## 2\. ... add an input... <input type="text" value="#bada55" class="my-color-field" data-default-color="#effeff" /> ## 3\. ... and call wpColorPicker function jQuery(document).ready(function($){ $('.my-color-field').wpColorPicker(); });
stackexchange-wordpress
{ "answer_score": 13, "question_score": 7, "tags": "plugin development, javascript, color picker" }
How can I get the last 5 element of this tax query? $args = array( 'post_type' => 'news', 'posts_per_page' => 5, 'post_status' => 'publish', 'order' => 'ASC', 'tax_query' => array( array( 'taxonomy' => 'week', 'field' => 'slug', 'terms' => $currweeknumber, ) ) ); $post = get_posts($args); I have a page which posts 5 news each week. I have a problem. A year passed since I started my blog and this `$args` query shows me the last year news, not the actual. This is because week number doesn't changed at all, it's the same value from 1 to 52 (basically I have 52 terms with the value of 1,2,3...etc). Is there any way to get the last 5 element of this array, not the first 5? I'm tried with `'order' => ''DESC'` but not worked.
add the 'date_query' parameter to your query and include the current year. $args = array( 'post_type' => 'news', 'posts_per_page' => 5, 'post_status' => 'publish', 'order' => 'ASC', 'tax_query' => array( array( 'taxonomy' => 'week', 'field' => 'slug', 'terms' => date("W", strtotime("this week")), ) ), 'date_query' => array( array( 'year' => date("Y") ) ) );
stackexchange-wordpress
{ "answer_score": 0, "question_score": 0, "tags": "custom post types, posts, custom taxonomy, tax query" }
Intercepting a add_action Assume that some other plugin or theme uses a add_action hook. Is there a way to determine if a specific hook is being used by someone else? Example: assume that a plugin has this code add_action ( 'publish_post', 'myCustomFunction' ); function myCustomFunction() { // does something } Can my plugin 'look' for the use of that hook into 'publish_post'? And can I remove that particular action hook before it fires?
You can use `has_action()`. It returns the priority of the hook if it exists, otherwise `false`. So check that the priority is not equal to `false` (and not just false-y, or being hooked at `0` will appear false) then use that to remove the hook. $priority = has_action( 'publish_post', 'myCustomFunction' ); if ( $priority !== false ) { remove_action( 'publish_post', 'myCustomFunction', $priority ); } There's also `has_filter()`, which does exactly the same thing (`has_action()` just calls `has_filter()`).
stackexchange-wordpress
{ "answer_score": 2, "question_score": 3, "tags": "plugins, hooks" }
How to make an meta_query optional? I added this snippet of code to my `functions.php` to be able to make a request to a custom post type and filter by `book_id` add_filter( 'rest_gallery_query', function( $args ) { $args['meta_query'] = array( array( 'key' => 'book_id', 'value' => esc_sql( $_GET['book_id'] ), ) ); return $args; } ); so with that I am able to make a request to '< `gallery` is a custom post type and `bookd_id` is one of its custom fields the issue I am having here is after this I can't do requests to `/wp-json/wp/v2/gallery` without `book_id` anymmore and I really need to be able to do it, how can I get rid of that situation? I was looking for a way to make this param optional but I didn't find anything yet
It's not so difficult. All you have to do is to add a condition and check if the `book_id` param is passed. You can even check if this param is correct (for example if the book_id should be a number, then you can check if it is): add_filter( 'rest_gallery_query', function( $args ) { if ( trim($_GET['book_id']) ) { // check if book_id is passed and is not empty, but you can modify this condition $args['meta_query'] = array( array( 'key' => 'book_id', 'value' => trim( $_GET['book_id'] ), // <- you don't need to esc_sql this ) ); } return $args; } );
stackexchange-wordpress
{ "answer_score": 2, "question_score": 3, "tags": "php, custom field, filters, meta query, rest api" }