INSTRUCTION
stringlengths
11
999
RESPONSE
stringlengths
0
999
SOURCE
stringlengths
16
38
METADATA
dict
ACF - Eliminate unnecessary data and print In ACF, the_field('battery'); outputs as follows : Battery : Sony Rechargeable Ni-MH 2200 mAh battery or Battery : Energizer AA Rechargeable Batteries 2300 mAh NiMH How can i achieve this (showing only mAh details) : Battery : 2200 mAh or Battery : 2300 mAh
You have to use a regex, in this case, to extract the needed value from a string: $string = 'Energizer AA Rechargeable Batteries 2300 mAh NiMH'; preg_match('/([0-9]+\s*mah)/i', $string, $capacity ); if ( isset( $capacity[0] ) ) { printf('Battery: %s', $capacity[0] ); } This regex `/([0-9]+\s*mah)/i` will look for any numbers followed by case insensitive `mah` combination. You can test this regex online here < Also, here is documentation on `preg_match` <
stackexchange-wordpress
{ "answer_score": 0, "question_score": 0, "tags": "advanced custom fields, regex" }
Number format for wp_count_posts() I'm trying to format my post my total post count in the header of my site. I have the number in there but would like it to format with the commas eg 1,500 not 1500. I know this is probably really basic but I'm still learning.. any help would be much appreciated. Cheers functions.php function wpb_total_posts() { $total = wp_count_posts()->publish; echo '' . $total; } Header.php <?php wpb_total_posts(); ?>
You can use the PHP function `number_format()`. function wpb_total_posts() { $total = wp_count_posts()->publish; echo number_format( $total, // your number 0, // number of decimal points '.', // decimal point separator ',' // thousands separator ); } Or, because you are using the default values anyway, you can shorten the function to: function wpb_total_posts() { echo number_format( wp_count_posts()->publish ); }
stackexchange-wordpress
{ "answer_score": 1, "question_score": 1, "tags": "posts, formatting" }
Change page name in admin list One of my customer has many pages that have the same titles, although their content is different. They would like to be able to give them "admin titles" in order to differentiate them in the admin list. I was thinking of adding an ACF extra field "Admin Title". If this field is filled, then on the page listing in the admin, I would like to use it. Is there an admin filter that is called when generating the page list ?
You can use `the_title` hook to change the title of the post in the admin, something like this add_filter( 'the_title', 'custom_post_title', 10, 2 ); function custom_post_title( $title, $post_id ) { // Return early if not in the admin if ( !is_admin() ) return $title; $post_type = get_post_type( $post_id ); // You only need to change the title for pages if ( 'page' !== $post_type ) return $title; $custom_title = get_field( 'your_custom_title_acf_key', $post_id ); // If custom title is present, display it instead of original if ( $custom_title ) { $title = $custom_title; } return $title; }
stackexchange-wordpress
{ "answer_score": 1, "question_score": 0, "tags": "pages, admin, wp list pages" }
How to exclude a category returned by get_categories from function.php? I have a plugin that create my website sitemap. It starts by getting all categories with `get_categories` and then gets all pages for each. However I have one category that must not be included then I did that in the plugin code: $args['exclude']=2; $cats = get_categories( $args ); The problem is that if the plugin replace the file my modiofication will be deleted, I tried with that: function exclude_cat($taxonomy, $args) { $args['exclude']=2; return $args; } add_filter('get_categories_taxonomy', 'exclude_cat', 10, 2); But then no category is returned at all, I think I'm not using it correctly but I don't find examples.
You'll find an appropriate filter in the `get_terms` function which is called by `get_categories`. See source code < We don't use any of the callback arguments in this case. We can use `array_filter` on the list of terms (WP_Term) objects. See < This allows us to remove a term with a particular ID add_filter( 'get_terms', function( $terms, $taxonomies, $args, $term_query ){ return array_filter($terms, function( $term ) { return $term->term_id !== 2; }); }, 10, 4 ); Note that `get_categories` by default only returns categories which have posts assigned, you can change that by adding `hide_empty => false` to the `$args` array.
stackexchange-wordpress
{ "answer_score": 0, "question_score": 0, "tags": "categories, filters" }
post_type internal ID? This may sound like a stupid question, but is there something like an ID associated with the post types (built in or custom) in WordPress? I'm not interested in the actual post id, but wondering if there's something like this: ID Post type slug ------------------------- 0 post 1 page 2 slider 3 section ... What I would need would be something like `get_post_type_id( $post_type_slug )` so that when I call `get_post_type_id( 'slider' )` it would return `2`. The reason: I'm building a post slider shortcode and I need a unique ID that could be in the form of `#{$post_type}-slider-{$id}`, to avoid duplicates and correctly apply JavaScript. Thanks!
**No there isn't, and it isn't necessary. Post type names are their own unique identifiers.** The primary reason there are no numeric IDs is because post types are registered on every page load in PHP, no table exists in the database for them, which means no row IDs. So there is no use for a unique ID that the post name doesn't already accomplish. For this reason, you're perfectly fine to use the post types name in your ID attributes, post type names can't clash. The same is true of taxonomy names, 2 taxonomies cannot share the same name.
stackexchange-wordpress
{ "answer_score": 1, "question_score": 0, "tags": "custom post types, shortcode, id, post type" }
Show admin menu and toolbar in admin post page Is there a way to still show the **admin toolbar** and/or the main wordpress **admin menu** in the admin post page? ![wordpress edit.php page]( ![wordpress post.php page](
What you see on that image is the _full-screen mode_ which is the default mode in the block editor (that applies to Pages, Posts and custom post types), and which is intended to help users to work without distraction. Secondly, there's also a note in `wp-admin/admin-header.php` which says that `// Default to is-fullscreen-mode to avoid jumps in the UI.` — `is-fullscreen-mode` is a CSS class added to the `<body>` tag indicating a full-screen mode. Therefore, the default mode should not be changed (programmatically). However, once the page has been loaded, you can turn off the full-screen mode by simply clicking on the three-dot button (which shows " _More tools & options_" when mouse-overed) on the top-right corner of the screen, and from the menu that appears, just click on the " **Fullscreen mode** " option: ![Toggle the Fullscreen mode in the block editor]( "A preview on WordPress 5.5.1") Hope that helps! :)
stackexchange-wordpress
{ "answer_score": 1, "question_score": 0, "tags": "admin menu, admin bar" }
How to dequeue wp_get_custom_css in Twenty Twenty Theme How to remove Additional CSS from loading. It loads as internal style sheet on every page. I am doing this but it is not working. if I `print_r(wp_get_custom_css());` It shows the same css. I want to disable it to load. add_action( 'wp_enqueue_scripts', 'mywptheme_child_deregister_styles', 11 ); function mywptheme_child_deregister_styles() { wp_dequeue_style( 'wp-custom-css' ); } ![Style](
That `style` HTML is added by WordPress using `wp_custom_css_cb()` and it's hooked to `wp_head` like so: add_action( 'wp_head', 'wp_custom_css_cb', 101 ); Which adds the custom/additional CSS in the document `head`. So if you don't want that to happen — or you'd rather add/load the CSS manually, you can add this to your theme `functions.php` file: remove_action( 'wp_head', 'wp_custom_css_cb', 101 );
stackexchange-wordpress
{ "answer_score": 1, "question_score": 2, "tags": "wp enqueue style" }
Adding post fields in wp-json/wp/v2/search I am trying to add the post (pages, posts) excerpt in the `wp-json/wp/v2/search` get endpoint but this endpoint seems to not take into account the `register_rest_field` method. add_action('rest_api_init', function() { register_rest_field('post', 'excerpt', array( 'get_callback' => function ($post_arr) { die(var_dump($post_arr)); return $post_arr['excerpt']; }, )); register_rest_field('page', 'excerpt', array( 'get_callback' => function ($post_arr) { die(var_dump($post_arr)); return $post_arr['excerpt']; }, )); }); This causes `wp-json/wp/v2/pages` and `wp-json/wp/v2/posts` to die, but `wp-json/wp/v2/search` works perfectly, although it renders posts and pages. Any idea how I can add my excerpt to the results of the `wp-json/wp/v2/search` route?
For the search endpoint, the object type (the first parameter for `register_rest_field()`) is `search-result` and not the post type (e.g. `post`, `page`, etc.). So try with this, which worked for me: add_action( 'rest_api_init', function () { // Registers a REST field for the /wp/v2/search endpoint. register_rest_field( 'search-result', 'excerpt', array( 'get_callback' => function ( $post_arr ) { return $post_arr['excerpt']; }, ) ); } );
stackexchange-wordpress
{ "answer_score": 5, "question_score": 4, "tags": "rest api" }
Can I pass parameters to the add_shortcode() function? As the title states, I need to pass at least one parameter, maybe more, to the `add_shortcode()` function. In other words, those parameters I am passing will be used in the callback function of `add_shortcode()`. How can I do that? Please note, those have NOTHING to do with the following structure `[shortcode 1 2 3]` where `1`, `2`, and `3` are the parameters passed by the user. In my case, the parameters are for programming purposes only and should not be the user's responsibility. Thanks
You can use a closure for that together with the `use` keyword. Simple example: $dynamic_value = 4; add_shortcode( 'shortcodename', function( $attributes, $content, $shortcode_name ) use $dynamic_value { return $dynamic_value; } ); See also Passing a parameter to filter and action functions.
stackexchange-wordpress
{ "answer_score": 1, "question_score": 0, "tags": "shortcode, parameter" }
How to fix mime-type and (after disabling nosniff) 404 errors for css and js files in staging site I set up a staging site from the live site with my hosting, A2 Hosting. The pages are all messed up, and in the browser console, I could see lots of mime type errors (photo for examples). The errors come from CSS and JS files from all the plugins and theme. ![Mime-type mismatches in Browser console]( I talked to hosting support, and they edited the .htaccess file to disable nosniff, so the browser can see what they really are. But now they are generating 404 Not Found errors in the Network tab of the browser developer tools. But if I copy one of the URLs from the error and put it in another browser tab, it comes right up, no problem. This makes no sense to me, and I would appreciate a pointer how to fix it.
I found there were two problems causing this: 1. There is some kind of server caching I apparently don't manage. I cleared that by adding a query to the URL (like staging.site.org/?a=b) and some things started being served, but many were still giving 404s. 2. There was a rewrite rule in .htaccess designed to prevent hotlinking things in wp-content, allowing google and my site only. That was not updated to the staging URL during creation of the staging. So the staging site was blocking itself! Sorry, I know this kind of thing would be impossible for anyone to solve unless you had full access to the site and tons of time to devote to it. I appreciate people looking.
stackexchange-wordpress
{ "answer_score": 0, "question_score": 0, "tags": "404 error, staging" }
Differentiation between index.php and page.php I am currently developing a theme in wordpress for learning purposes. To set out to you my page hierarchy I have the following: * index.php: fallback for all website pages * home.php: blog page * front-page.php: static front page * page.php: default fallback for individual pages * single.php: single post page * header.php and footer.php I wanted to know what difference between an index.php and a page.php should display? On my index.php, I have only the header(); and footer(); functions. On my page.php, I have my main content div with the standard loop that outputs my page posts from wordpress, with the exclusion of the header and footer functions Would my index and page files be correct in outputting the content like this? Thanks.
> Would my index and page files be correct in outputting the content like this? No. If you attempt to search, or browse posts by tag or category, then you won't see any posts because your index.php file doesn't loop through any posts, according to your description. _All_ templates in the template hierarchy should use the standard loop because WordPress will query the correct posts and then use the appropriate template to display them. As you can see from the template hierarchy diagram, there are several post archives that will use your theme's index.php template, so it's important for that template to include the loop. The only exception is the 404.php template, which will not need to display any posts (since none have been found). Since you have single.php and page.php templates in your theme, your index.php file only needs to be optimised for displaying lists of multiple posts, for things like date and category archives, and search results.
stackexchange-wordpress
{ "answer_score": 1, "question_score": 0, "tags": "templates, template hierarchy" }
How Do I Use a ACF Custom Field To Add A Slider ID? soliloquy( the_field( 'slider' ) ); This is my code to add the ID for a slider from a ACF number field to a slider function call however it outputs the ID and doesn't execute the soliloquy function. I think it might have something to do with the single qoutes. Not sure how to wrap the slider ID in single qoutes
You need to use **get_field()** function instead. It will RETURN the value instead of printing. So, your code will be: soliloquy( get_field( 'slider' ) );
stackexchange-wordpress
{ "answer_score": 1, "question_score": 0, "tags": "advanced custom fields" }
How can I display tags as categories? I'm using the "Pages with category and tag" plugin because my website uses individual long pages as posts. I would like to make a gallery of the past posts (sort of like an archive section), but my theme can filter posts only by categories. I would prefer not to use categories but rather tags, since they are better suited for our content. How can I merge the categories and tags so that my theme can filter these pages using both?
If you can setup url query parameters and when user navigates to tagfillterPage page with wp_query it should work. < $querytag = $_GET['filltertag']; $args = array( 'tag' => $querytag ); // Custom query. $query = new WP_Query( $args ); // Check that we have query results. if ( $query->have_posts() ) { // Start looping over the query results. while ( $query->have_posts() ) { $query->the_post(); // Contents of the queried post results go here.} } // Restore original post data. wp_reset_postdata();
stackexchange-wordpress
{ "answer_score": 1, "question_score": 0, "tags": "categories, filters, pages, tags, blog" }
Cache WP remote_get HTTP Response using Transients Using wp_remote_get keeps pinging the API on every page load. Which increase the server resource. Is it possible to cache the response of the API store it using Transients and use it for next 5 minutes instead of keep pinging everytime? And After 5 Minutes it should send request again and rewrite the stored value. Here is my code for API Request. How to do this? I'm new to this. Help me please function display_api_response() { $api_url = " $response = wp_remote_get($api_url); if ( 200 === wp_remote_retrieve_response_code($response) ) { $body = wp_remote_retrieve_body($response); if ( 'a' === $body ) { echo 'A wins'; }else { // Do something else. } } } add_action( 'init', 'display_api_response' );
function display_api_response() { $body = get_transient( 'my_remote_response_value' ); if ( false === $body ) { $api_url = " $response = wp_remote_get($api_url); if (200 !== wp_remote_retrieve_response_code($response)) { return; } $body = wp_remote_retrieve_body($response); set_transient( 'my_remote_response_value', $body, 5*MINUTE_IN_SECONDS ); } if ('a' === $body) { echo 'A wins'; } else { // Do something else. } } add_action('init', 'display_api_response'); At first, the transient doesn't exist, so we send a request and save the `$body` as a transient value. Next time, if the transient exists, we skip sending request. Check the Transient Handbook for more information.
stackexchange-wordpress
{ "answer_score": 1, "question_score": 1, "tags": "plugins, wp api, http api" }
What are the meta fields for an attachment? I'm trying to find all the meta fields that are used for an attachment: like Title, alternative text, description and caption . I've looked all over and the only one I was able to find was for an Alternative text, which is `_wp_attachment_image_alt`.
You can easily inspect all the metadata for any post like so: // 123 is the (attachment) post ID var_dump( get_post_meta( 123 ) ); And in a default WordPress setup with no plugins or theme which add custom metadata to the image attachment post, the metadata you'd get are: * `_wp_attached_file` — string, the image file (path and name) for the attachment post * `_wp_attachment_metadata` — array (serialized), the sizes for the image like 'thumbnail' (including original size), and metadata from EXIF/IPTC info. * `_wp_attachment_image_alt` — string, the image's alternative text As for the other details like the image title, they are in the post data (in the posts database table), so you can for example use `wp_update_post()` to update these details: * `post_title` — image title * `post_excerpt` — image caption * `post_content` — image description
stackexchange-wordpress
{ "answer_score": 1, "question_score": 0, "tags": "functions, images, post meta, attachments" }
Am receiving more than thousand mails in single day from '[email protected]' continuously Am using 'WP Offload SES Lite' Plugin to collect Question & Answer through forms. But yesterday I was receiving thousands of mail in a single day continuously. I think someone tried to hack the site. Can you please tell me how to protect from these kinds of attacks? ![enter image description here]( ![enter image description here](
You should add a reCaptcha to your form, follow this tutorial: <
stackexchange-wordpress
{ "answer_score": 0, "question_score": 0, "tags": "forms, sql, email, hacked" }
Is there a PHP function that will return the block ID generated by WordPress? I've tried the `parse_blocks()` function, however it returns all of the blocks. I'm needing to narrow it down to just the current block's ID. Is there a PHP function for that? I'm needing get the unique ID for the block so I can set a transient.
You can iterate on your parsed blocks to get the right block. $blocks = parse_blocks( $post->post_content ); foreach ( $blocks as $key => $block ) { if ( 'block_xxxxx' === $block[ 'id' ] ) { // do some action here } }
stackexchange-wordpress
{ "answer_score": 0, "question_score": 0, "tags": "php, functions, block editor" }
Custom Gutenberg-Block esnext pass variables I am trying to create a Block with @wordpress/create-block, for this you have to use exnext. I`m not pretty good with JS at the moment, still learning. So far it is working (the block appears in the editor). The files are created with separate files and export functions. index.js with import Edit from './edit'; /** * @see ./edit.js */ edit: Edit, edit.js with export default function Edit({className, props}) { console.log(props); return ( <div> <p> Text </p> </div> ) } The className is available in the Edit function `export default function Edit({className}) { ... }`, but I cannot get `props` variable.
The problem in your "edit" file is that your `Edit()` function in there is _unpacking/destructuring_ the props, hence `props` is no longer defined or what you expected it to be. So you should do `function Edit( props )` and not `function Edit({className, props})` — and it should be noted that `className` is in that props, i.e. `props.className`. function Edit( props ) { console.log( props.className, props ); } // .. Or when unpacking the props object: // Assuming your block got an attribute named myAttribute. function Edit( { attributes, setAttributes, className } ) { console.log( className, attributes.myAttribute ); } I hope that helps and I suggest you to check, if you haven't already done so, the block editor handbook, e.g. the "Edit and Save" section. BTW, you don't actually have that `import Edit from './edit';` in the `edit.js` file, do you?
stackexchange-wordpress
{ "answer_score": 1, "question_score": 0, "tags": "javascript, block editor" }
Add value in user table when user is created I am trying to insert a value into a column after a user registers. Sadly after my test I get the error "Write Error" what could be wrong with the hook? function org_teammember( $user_id ) { $teammember = 'yes'; $sql = "INSERT INTO wp_usermeta (ocp_team_member)". "VALUES('$user_id','$teammember')"; $result = mysqli_query($wpdb, $sql) or die('Write Error!'); }```
Used the method of @geouser > Why don't you just use a function WordPress already has update_user_meta()? developer.wordpress.org/reference/functions/update_user_meta There is no need to write a custom SQL queries
stackexchange-wordpress
{ "answer_score": 0, "question_score": 1, "tags": "users, user registration" }
Get Text Domain For Transalation Is there a function which can be used to get the themes text-domain? For example, if i want to provide this code to users without them needing to swap out the text-domain, can this be done, rather than this : register_sidebar( array( 'name' => __( 'Widget Area', 'twentynineteen' ), 'id' => 'widget-id', )); Use something like this so they don't need to change the text-domain to match the theme they are using : register_sidebar( array( 'name' => __( 'Widget Area', get_text_domain() ), 'id' => 'widget-id', ));
No, there isn't. The text domain needs to be hard coded, otherwise it can't be read by localization tools which parse the code without executing it. See this note from the Internationalization documentation > The text domain should be passed as a string to the localization functions instead of a variable. It allows parsing tools to differentiate between text domains. Example of what not to do: > > > __( 'Translate me.' , $text_domain ); > The string itself also cannot be a variable or function for the same reason.
stackexchange-wordpress
{ "answer_score": 1, "question_score": 0, "tags": "translation" }
SVG not displaying in Media Tab in Backend I addes this code to allow SVG Uploads to the Media Library of wordpress: function upload_svg ( $svg_mime ){ $svg_mime['svg'] = 'image/svg+xml'; return $svg_mime; } add_filter( 'upload_mimes', 'upload_svg' ); define('ALLOW_UNFILTERED_UPLOADS', true); Than I added some SVGs to the Media Library. Using them works perfectly fine. The only Issue I have is that they will not be displayed in the Media Library. On other Pages in the Backend they display fine. Is there anything I can do to display them in the Media Tab aswell? I couln't find anything online on how to fix this issue.
This is the solution to allow SVG upload and preview to Media area of WordPress: <
stackexchange-wordpress
{ "answer_score": 0, "question_score": 0, "tags": "uploads, media, thumbnails, svg" }
How to remove images from my plugin page in WP Directory? I can't understand why, but I can't rid of old (unnecessary) screenshots of my plugin in WP Directory. I've removed `assets` folder from each version in `tags`, removed `assets` folder from `trunk`, made commit, but on the plugin's page on WP Directory those images still here. If I hover cursor over some unnecessary image - I'll see hash of commit which firstly contain this image. How to get rid of this image?
Needed to use `svn delete` command to delete files, and then commit the changes. Screenshot: <
stackexchange-wordpress
{ "answer_score": 1, "question_score": 1, "tags": "plugin development, svn" }
How to schedule Automatic Wordpress Plugin and Core updates for night times I don't want to update plugins within business hours. Is there a way to schedule for after 1 am? Maybe via a hook or a setting in wp-config.php?
You could create a cronjob that runs on 1am every 24 hours. With WP CLI this would be something like: wp core update && wp plugin update --all && wp theme update So you just create a .sh script, put the above in it, and run the script with a cronjob.
stackexchange-wordpress
{ "answer_score": 2, "question_score": 1, "tags": "automatic updates" }
Why title_li ='' not working I want to hide the 'Categories' and used the following code <?php $args = array( 'parent' => 33, 'show_count' => 1, 'title_li=' => __( '' ), 'hide_empty' => 0, ); wp_list_categories($args) ?> But it is not working, why? Thank you.
Because the parameter name is `title_li` and not `title_li=`. It also doesn't make sense of using `__( '' )`, so I'd change that to just `''`. // When the args is a query string, title_li= works. $args = 'title_li='; // But when the args is an array, use just title_li. $args = array( 'title_li=' => '', // bad 'title_li' => '', // good );
stackexchange-wordpress
{ "answer_score": 1, "question_score": 0, "tags": "categories" }
How to properly enqueue jQuery knob on Wordpress without conflict? I'm building a plugin and I want to use jQuery Knob but it seems like using this method: plugins_url( '/assets/js/jquery.knob.min.js, . . . . . Have conflicts with other plugins? How to convert it like this? wp_enqueue_script( 'jquery-ui-widget' ); wp_enqueue_script( 'jquery-ui-mouse' ); wp_enqueue_script( 'jquery-ui-accordion' ); wp_enqueue_script( 'jquery-ui-autocomplete' ); wp_enqueue_script( 'jquery-ui-slider' );
If you want to just enqueue a script by name then you have to register it first with wp_register_script: wp_register_script( 'jquery-knob', plugins_url( 'assets/js/jquery.knob.min.js', __FILE__ ), array( 'jquery' ), '1.2.11' ); : wp_enqueue_script( 'jquery-knob' ); However that's only really useful when you're registering a script to be available as a dependency for other scripts, which I don't think you are here. Instead it's easier to register and enqueue it in one go, which you should do from a wp_enqueue_scripts hook: function enqueue_jquery_knob() { wp_enqueue_script( 'jquery-knob', plugins_url( 'assets/js/jquery.knob.min.js', __FILE__ ), array( 'jquery' ), '1.2.11' ); } add_action( 'wp_enqueue_scripts', 'enqueue_jquery_knob', 10, 0 );
stackexchange-wordpress
{ "answer_score": 0, "question_score": 0, "tags": "plugins, plugin development, javascript, jquery, wp admin" }
How to distinquish wordpress served links from non-wordpress served links I am working on a legacy code where part of the website uses WP and other part ASP.net etc. Is there an easy way to tell me what content is coming from WP vs Non-WordPress? Since the codebase is large this can help me understand the flow of information.
This depends very much on you setup and how you want to be able to see this. If you look in the source code of a page, you are very likely to be able to see which page is WP generated, because there will be strings like `wp-content` and `wp-includes` present (for instance because `jquery` is loaded by default). You could also add a specific code to the head of your site like this: add_action ('wp_head','wpse376765_add_code'); function wpse376765_add_code () { echo '<meta name="wpmademe">'; } If you want it to be visible in the page itself, the easiest way would be to attach a little marker for admins only by including this in the `functions.php` of your theme: add_action ('wp_footer','wpse376765_add_code_to_footer'); function wpse376765_add_code_to_footer () { if (is_admin()) echo '<span>WP made me</span>'; }
stackexchange-wordpress
{ "answer_score": 2, "question_score": 0, "tags": "plugins" }
modify menu item links dynamically on our wordpress site we use utm_source in the querystring to determine the campaign that brought a customer to our site. I need to dynamically add the passed utm_source from the initial page to all the menu items on the site. How can I modify all links in the wordpress menus to add the querystring variables?
Can be changed using filter add_filter('wp_get_nav_menu_items', 'add_utm_to_links', 10, 3); function add_utm_to_links($items, $menu, $args) { foreach($items as $item) { if(!empty($item->url)) { $item->url .= strchr($url, '?') === false ? '?' : '&'; $item->url .= 'utm=value'; } } return $items; }
stackexchange-wordpress
{ "answer_score": 2, "question_score": 0, "tags": "menus, theme customizer" }
Vimeo froogaloop Very much a newbie here, but I'm trying to use this idea to disable forward seeking in Vimeo clips embedded on a Wordpress site To my functions.php I've added function frogaloop_scripts() { wp_register_script('snippet', ' wp_register_script('frogaloop',' } add_action( 'wp_enqueue_scripts', 'frogaloop_scripts' ); On a page with an embedded video, I've got <iframe id="video1" src=" width="630" height="354" frameborder="0" webkitallowfullscreen="" mozallowfullscreen="" allowfullscreen=""></iframe> Where 'video1' matches the iframe label in the codepen example. When I load the page source, I can't even see frogaloop being listed, so I'm not sure the enqueuing is even happening... Where am I going wrong with this ?
> so I'm not sure the enqueuing is even happening No, it's not, because you only registered the scripts, but never enqueued them — which should be done using `wp_enqueue_script()`. Also, you should make `frogaloop` as a dependency for your `snippet.js` script. Hence, register the `frogaloop` script before your `snippet.js` script. // Register the scripts. wp_register_script( 'frogaloop', ' array(), null ); // The third parameter is the script dependencies. wp_register_script( 'snippet', get_template_directory_uri() . '/js/snippet.js', array( 'frogaloop' ) ); // Then enqueue them. But you just need to call: wp_enqueue_script( 'snippet' ); // because frogaloop will also be enqueued because it's a dependency for your // snippet.js script. Now that should work.
stackexchange-wordpress
{ "answer_score": 2, "question_score": 1, "tags": "javascript, vimeo" }
How to display all posts not in a post_format Using WP_Query() I want to display all posts -except- those with the 'image' post_format. I tried this, but it did not work. $args = array( 'relation' => 'NOT', 'tax_query' => array( array( 'taxonomy' => 'post_format', 'field' => 'slug', 'terms' => array('post-format-' . $post_format), ) ), 'paged' => get_query_var('paged') ); query_posts( $args );
It didn't work because your tax query is missing the operator which should be set to `NOT IN`. So just add it like so: 'tax_query' => array( array( 'taxonomy' => 'post_format', 'field' => 'slug', 'terms' => array( 'post-format-' . $post_format ), 'operator' => 'NOT IN', ) ), And please, **avoid using`query_posts()`** — use `new WP_Query()` or `get_posts()` instead — or hooks such as `pre_get_posts` for modifying the query parameters.
stackexchange-wordpress
{ "answer_score": 1, "question_score": 0, "tags": "wp query, post formats" }
How to detect if this post is a woocommerce product? Let's say I have post has the ID 243. Is there a function that detects if this is a woocommerce product or no. maybe the function return true/false
You can Use Condition for check product or post if(is_product() && get_the_id() == 243) { //do stuff }else{ //do stuff }
stackexchange-wordpress
{ "answer_score": 2, "question_score": 2, "tags": "woocommerce offtopic" }
Single product page doesn't display price I have the following code to display price once entering single product page. <?php global $woocommerce; $product = new WC_Product(get_the_ID()); echo $product->get_price_html(); //Shows the price ?> I have tried serval variation of this code, but they all either error or empty value. Although `<?php echo get_the_title() ?>` does work. What can be causing `get_price_html()` to echo empty value?
If you have the product's ID you can use that to create a product object: $product= wc_get_product( $product_id ); Then from the object you can run any of WooCommerce's product methods. $product->get_regular_price(); $product->get_sale_price(); $product->get_price();
stackexchange-wordpress
{ "answer_score": 1, "question_score": 0, "tags": "woocommerce offtopic" }
Whitespace between product image and gallery on initial load of lightbox product page I'm trying to understand why whitespace appears between the main product image and the product gallery on this page: < Clicking on the middle image will remove the whitespace. Why would it be doing this? Cheers
Ok, so eventually managed to figure out that it was due to a couple of optimization plugins that were interfering with WooCommerce's image slider: JetPack's lazy loading and SG Optimizer. Deactivated SG Optimizer and added the following to my child theme's functions.php: function is_lazyload_activated() { $condition = is_product(); if ($condition) { return false; } return true; } add_filter('lazyload_is_enabled', 'is_lazyload_activated'); Now things are working again. Shame that can't have the optimization plugins working at the same time. At least the code above allows lazy loading on all pages except for the product pages though.
stackexchange-wordpress
{ "answer_score": 1, "question_score": 0, "tags": "woocommerce offtopic, lightbox" }
Non-existent page returns code 200 I have a page like mysite.com/contacts/ If I enter non-existent urls like: mysite.com/contacts--/ mysite.com/contacts%20/ i get status 200 and the page opens mysite.com/contacts/ although if I enter: mysite.com/contacts1/ As expected, I am getting a 404 error. How can I implement error handling at the CMS level so that non-existent pages return a page with a 404 error template? There may be some plugin that implements URL management?
**That's not what's happening** , when you visit `/contacts--/` it doesn't return a 200 code, but instead it returns a `301` redirect code. The browser then follows this redirect and heads to `/contact` and it's `/contact` that returns `200` code. This is because `/contact` is the canonical URL of that page, and WordPress redirects to canonical pages out of the box for improved SEO. It should also be adding a meta tag to the header containing the canonical URL to avoid duplicate content penalties.
stackexchange-wordpress
{ "answer_score": 2, "question_score": 1, "tags": "404 error" }
What structure should post_content have in the database? Let me start off by saying that I have no WordPress experience at all so I may be asking a really stupid question. What I need to do is transfer a bunch of articles from a old MySQL database to a WordPress site. Now I found wp_insert_post and I can get all the data from the old DB. The problem starts with the article images. In the WordPress DB there seems to be a `<figure class="wp-block-image size-large"><img src="hard path to image here" alt="" class="wp-image-4066"/></figure>` tag that points to the exact image. Problem is that it is surrounded by, what I would call strange comments, that look like this : <!-- wp:image {"id":4066,"sizeSlug":"large"} --> <!-- /wp:image --> This id seems to be the ID of the image that is made a attachment type post in the same table. My question is are these comments necessary or can I just generate the tag ?
Those comments have been added by the Gutenberg block editor. If you remove them you'll no longer be able to edit those blocks in the admin using Gutenberg.
stackexchange-wordpress
{ "answer_score": 1, "question_score": 1, "tags": "posts, database" }
List blocks created by a specific block plugin One way is to list all the posts and search using `[has_block][1]` but it seems inefficient. Is there a faster way to do this?
So I had to extend the wordpress rest api by adding a custom endpoint that filtered all the posts using `has_block` and return the results.
stackexchange-wordpress
{ "answer_score": 0, "question_score": 1, "tags": "posts, block editor" }
Redirecting from login I want my site to redirect after login to site_url('/') for all users except 'administrator' I also want the admin_bar showing for certain roles ie event_planner. It is all working except that when and event_planner logs on and then clicks on the admin bar to go into admin it redirects to '/'. The hook being used to redirect is 'admin_init' which is clearly wrong. Is there another hook I could use to initially redirect to / on login but not when pressing the dashboard on the admin bar. Thanks
There's a filter called `login_redirect`. add_filter( 'login_redirect', 'wpse377295_login_redirect', 10, 3 ); function wpse377295_login_redirect( $url, $request, $user ) { if ( is_wp_error( $user ) ) { // It's possible that the $user param is a WP_Error. If so, bail out. return $url; } if ( ! user_can( $user, 'update_core' ) { // Only admin users can update core, normally. $url = site_url( '/' ); } return $url; } There's a more complete example in the filter documentation's User Contributed Notes. ## References * `login_redirect` * `user_can()`
stackexchange-wordpress
{ "answer_score": 3, "question_score": 0, "tags": "hooks" }
How do you find a file in the media library using the file URL? We have about 2000 files in our media library and we are working on an audit to organize the files and create a name hierarchy. But until that is done, I am trying to locate a handful of specific files to replace. I don't know what the files are named in Wordpress, I only have the URL to download the file. Is there a way to search for the file in the dashboard using the URL?
Based on my research, you would need to run a query on directly on the database using WPDB. So you would do something like this: Add this in your `functions.php` file: // retrieves the attachment ID from the file URL function get_image_id($image_url) { global $wpdb; $the_attachment = $wpdb->get_col($wpdb->prepare("SELECT ID FROM $wpdb->posts WHERE guid='%s';", $image_url )); return $the_attachment[0]; } And then you can apply it wherever you like this way: $attachment_url = ' $attachment_id = get_image_id($image_url); `$attachment_id` will have the attachment ID so you can do whatever you want with it.
stackexchange-wordpress
{ "answer_score": 0, "question_score": 0, "tags": "media library, wp filesystem" }
Add attribute to script loaded by the theme I was looking for a method to add the **data-cfasync= "false"** attribute to a javascript loaded by the theme itself. My theme load the script <script type="e350ac6f596d90da70624b6d-text/javascript" src=' id='jquery-fluidbox-js'> And I would like to have <script data-cfasync="false" type="e350ac6f596d90da70624b6d-text/javascript" src=' id='jquery-fluidbox-js'> Basically just the inclusion of my attribute letting everything unchanged The script is loaded by the theme with wp_enqueue_script( 'jquery-fluidbox', get_parent_theme_file_uri( 'assets/js/jquery.fluidbox.min.js' ), array(), '2.0.5', true ); I've seen this solution Adding Additional Attributes in Script Tag for 3rd party JS but it's 7 years old and doesn't seem to work for me.
The code referenced in your question is still good. I double checked, and this worked for me: function wpse_script_loader_tag( $tag, $handle ) { if ( 'jquery-fluidbox' !== $handle ) { return $tag; } return str_replace( ' src', ' data-cfasync="false" src', $tag ); } add_filter( 'script_loader_tag', 'wpse_script_loader_tag', 10, 2 ); (I tested with a different script handle, but that won't matter): ![enter image description here](
stackexchange-wordpress
{ "answer_score": 1, "question_score": 1, "tags": "filters, javascript" }
Category selectable homepage I've got a local Wordpress install that I've tried to make customisable by users, so it only shows pages from categories they have selected. I've used the code that I've found in the thread How to Set an Individual Homepage for Each User? and while it works, it breaks the menu on every page, it just dissapears. Example before: < And After: < Any help would be appreciated. Thank you in advance.
It's important to add guard clauses to prevent modification of other queries. (For example, menus). We are trying to modify the main query here, so we should bail if this is not the main query. function my_get_posts( $query ) { // Bail if this is not the main query. if ( ! $query->is_main_query() ) { return; } // Other guard clauses to ensure we don't affect queries unintentionally. // Sounds like you are just trying to target the homepage, so we could check for that too. if ( ! is_home() ) { return; } // We only need to modify the query for logged in users. if ( ! is_user_logged_in() ) { return; } // Modify the query as needed... } add_action( 'pre_get_posts', 'my_get_posts' ); // Note that pre_get_posts is an action, not a filter.
stackexchange-wordpress
{ "answer_score": 0, "question_score": 1, "tags": "customization, categories, homepage" }
Cannot changing login button color, have tried theme, plugins... is it GoDaddy managed? I have added this code into my theme Customization and also Simple Custom CSS plugin .wp-core-ui #login .button-primary { background: #7e0001 !important; background-image: none !important; border-color: #7e0001; } For the life of me I cannot that code override the 'default blue' of the WordPress login button. The only plugin that works is "Login Press" which seems to use the exact same CSS as me, but somehow WordPress pays attention to it and not my theme CSS. I don't need to style the whole thing I just want to colorize the damn button. Is it me? Is it GoDaddy WordPress Managed hosting?
The login page doesn't load your theme's stylesheet. If you want to include extra CSS on your login page then you should hook login_enqueue_scripts and write out an extra `<style>` tag there, or include another CSS file (or even your theme's full CSS file if you want to). You could also use login_head, and there's an example of including another CSS file in the login_head documentation, but it sounds like login_enqueue_scripts is more correct.
stackexchange-wordpress
{ "answer_score": 1, "question_score": 0, "tags": "themes, buttons" }
Fire a code when permalinks updated I would like to execute some php code when permalinks updated, I think some plugins I'm using them updates permalinks programmatically sometime and this breaks my some slug rewrite settings, at this point I need to run code when permalinks updated. Is there any filter or event listener to make me able to this.
From what I know you can use the post_updated or the save_post hooks < < Hope that this help. If you need any other info please let me know. Update: Sorry for my misunderstanding. You can use the the_permalink filter. Below you have the docs <
stackexchange-wordpress
{ "answer_score": 0, "question_score": 0, "tags": "permalinks, filters, rewrite rules" }
Set class if a meta value is set within post archive I'm _attempting_ to add a class to posts when the meta key 'checkbox' is clicked. Here's what I have: <?PHP $checkbox = get_post_meta($post->ID, 'checkbox', true); if (!empty($checkbox)){ $has_video = 'icon-has_video'; } else {$has_video = '';} ?> <a class='<?php echo $has_video; ?>' href='<?php the_permalink(); ?>'> ... but so far it's not working. Any suggestions?
i suggest you check the the value of $checkbox by either checking checkbox under meta_key column in wp_postmeta or *your prefix_postmeta table in your database or simply do var_dump($checkbox); for testing if its 0 or null or an empty string or so then your if condition will not return true and $has_video will not be assigned to 'icon-has_video'.
stackexchange-wordpress
{ "answer_score": 0, "question_score": 0, "tags": "custom field, post meta, metabox, meta value, post class" }
how to display sidebar on pages in wordpress I want to display custom field's content in the sidebar on specific pages in WordPress so can anyone have an idea about it then please share it with me. Thanks In Advance...
First you have to register the sidebar if you haven`t done yet with `register_sidebar( $args );`, then display it in the page: `dynamic_sidebar( $sidebar );` see documentation at: <
stackexchange-wordpress
{ "answer_score": 2, "question_score": 0, "tags": "pages, sidebar, the content" }
WP components no style I'm trying to build a plugin menu using wordpress components but it appears all the styles are missing. For ex. the button isn't colored the primary(Blue) in the following sandbox.. < What am I missing?
Looks like I had to just import the package style sheet located at `node_modules/@wordpress/components/build-style/style.css`
stackexchange-wordpress
{ "answer_score": 1, "question_score": 0, "tags": "admin menu, admin css" }
Built-in image lazy loading: Does it come with a polyfill for older browsers? It's neat that WordPress now automatically adds the `loading="lazy"` attribute to images. My question is: Does WP now also have a built-in JS polyfill for browsers that don't support the `loading` attribute? CanIUse.com reports less than 75% global browser support of the attribute.
No, it doesn't. Browsers that do not support the attribute will just continue loading images like normal, so it wasn't really necessary to include one. If you want to add one yourself, there are others available that you could include yourself, such as this one.
stackexchange-wordpress
{ "answer_score": 0, "question_score": 0, "tags": "images, javascript, media" }
How to add a gradient component to a custom block I can't find any useful information in Gutenberg Handbook. Here is information about adding gradients, but it only works for some core blocks. I use `ColorPalette` to create colors (or to use the color picker) but still don't know how to use gradients. I also found `PanelColorSettings` but still without success. I am looking for instructions/documentation on how to add this component: ![enter image description here](
**The documentation for that control does not exist at this time. Instructions have not been written yet. It is an experimental component.** * * * You need to use an appropriate control in your blocks Edit component. Note that these are very new components, their design will likely change, _it should be considered experimental and unstable_. There is the `GradientPicker` component, < And `ColorGradientControl` < <ColorGradientControl { ...otherProps } onColorChange={ onChange } colorValue={ value } gradients={ [] } disableCustomGradients={ true } />
stackexchange-wordpress
{ "answer_score": 2, "question_score": 0, "tags": "plugin development, block editor" }
Data Validation in wordpress In my theme, i am grabbing user input with get_option() and according to that input i want to i want to declare a new variable and print in my single.php file. For example: <?php $tutorial_condition = get_option( 'tutorials_creater' ); if ( $tutorial_condition == 1 ) { $second_col_class = 'col-9'; } else { $second_col_class = 'col-2'; } ?> now when i echo $second_col_class variable in my php files it works fine. But when i run themecheck plugin it shows an error like this. "Possible data validation issues found. All dynamic data must be correctly escaped for the context where it is rendered." i want to echo that variable like below. <div class="<?php echo $second_col_class; ?>"> //my code here.. </div> I cannot use isset() function because it just returning true or false. Is there any alternative to this?
Please see this Codex article for further guide, but in your case, you would use `esc_attr()` to escape the `$second_col_class` value which is being used in an HTML attribute, namely `class`: <!-- bad --> <div class="<?php echo $second_col_class; ?>"> <!-- good --> <div class="<?php echo esc_attr( $second_col_class ); ?>"> <!-- good --> <div class="<?php esc_attr_e( $second_col_class, 'text-domain' ); ?>">
stackexchange-wordpress
{ "answer_score": 1, "question_score": 0, "tags": "theme development, validation" }
WP_Query Filtred by author name ( Return null ) I want to list all pages whose author has a specific name but WordPress returns null values $args = array( 'author_name '=> 'admin', 'post_type'=>'page' ); $pages = new WP_Query( $args ); foreach( $pages as $page ) { var_dump( $page->post_title ); } result is NULL NULL NULL NULL NULL NULL NULL NULL NULL NULL string(4) "test" NULL NULL NULL NULL NULL NULL NULL NULL NULL NULL NULL NULL NULL NULL NULL NULL NULL NULL NULL NULL NULL NULL NULL NULL NULL NULL NULL NULL NULL NULL NULL NULL NULL NULL NULL
That's not how `WP_Query` works, it isn't what the documentation says either. **`WP_Query` is not a function.** `foreach` needs an array, or something that can be iterated on, but you've given it a `WP_Query` object. Instead, look at the documentation or tutorials, all of them follow this basic pattern for a standard post loop: $args = [ // parameters go here ]; $query = new WP_Query( $args ); if ( $query->have_posts() ) { while ( $query->have_posts() ) { $query->the_post(); // display the post the_title(); the_content(); } wp_reset_postdata(); } else { echo "no posts were found"; }
stackexchange-wordpress
{ "answer_score": 3, "question_score": 2, "tags": "wp query" }
Fatal error: require_once(): Failed opening required i am getting below error. Warning: require_once(C:\inetpub\vhosts\ashahealth.com\httpdocs/wp-includes/wp-db.php): failed to open stream: No such file or directory in C:\inetpub\vhosts\ashahealth.com\httpdocs\wp-includes\load.php on line 468 Fatal error: require_once(): Failed opening required 'C:\inetpub\vhosts\ashahealth.com\httpdocs/wp-includes/wp-db.php' (include_path='.;.\includes;.\pear') in C:\inetpub\vhosts\ashahealth.com\httpdocs\wp-includes\load.php on line 468 There has been a critical error on your website. Please check your site admin email inbox for instructions. For reference please find the below url <
wp-db.php file was missing in wp-includes.
stackexchange-wordpress
{ "answer_score": 1, "question_score": 0, "tags": "plugins, plugin development, multisite" }
Show Post Types customized in Template Page My plugin has custom Post Types that open on a custom page triggered by the following hook: `add_filter ('template_include', 'taxonomy_template'); // PRINTING PAGE` however, this page only appears when I access the menu: > Settings > Permanent Links and saved without even changing anything, is there a hook that makes this check and saves automatically?
The solution found was to update the rewrite rules right after registering my new post type, using this code at the end of the function: flush_rewrite_rules();
stackexchange-wordpress
{ "answer_score": 0, "question_score": 0, "tags": "custom post types, hooks" }
Why does modifying the "read more" link remove the link class? I'm using the following code (found on the WordPress.org site) to modify my `(more…)` text: //Modify "read more" text function modify_read_more_link() { return '<a class="more-link" href="' . get_permalink() . '">(Continue…)</a>'; } add_filter( 'the_content_more_link', 'modify_read_more_link' ); The code works as expected, in the sense that `(more…)` is properly replaced by `(Continue…)`, and the link works as intended. However, there is a peculiar issue: The class `more-link` has disappeared, which means styling doesn't work. I attempted to circumnavigate the issue by adding styling inline (`return '<a style="font-size:0.8em;" href="' . get_permalink() . '">(Continue…)</a>';`) but that hasn't worked either. **My Question** : Why has the class `more-link` disappeared, and how can I restore it? _Note:_ I add the code above to `functions.php`; I'm not using a child theme.
Perhaps there is an issue with the "Ellipsis" HTML character you are using? function modify_read_more_link() { return '<a class="more-link" href="' . get_permalink() . '">( Continue &hellip; )</a>'; } add_filter( 'the_content_more_link', 'modify_read_more_link' );
stackexchange-wordpress
{ "answer_score": 0, "question_score": 0, "tags": "functions, read more" }
WP-CLI plugin install causes PHP fatal error - Using $this when not in object context When running **sudo wp install plugin pluginname --allowroot** It causes an error: _PHP Fatal error: Uncaught Error: Using $this when not in object context in /var/www/html/wp-content/plugins/pluginname/blocks.php:89_ We have a custom plugin that has this line: class Block{ public static function Run() { add_action('enqueue_block_editor_assets',array($this,'RegisterBlock')); //complains on this line When installing via WP admin - it works fine. But when using WP-CLI it fails. Any help will be appreciated
public static function Run() { The "static" here means this function doesn't have an object context i.e. it's intended to be called as `Block::Run()` without actually making a Block. That said, `$block = new Block(); $block->Run();` will still work, but it still doesn't have $this set inside the method. Instead you can use the class name instead of $this to make a callable for a static method: class Block{ public static function Run() { add_action('enqueue_block_editor_assets', array('Block', 'RegisterBlock') ); But I've no idea how the original code is working in wp-admin. Is it code definitely being called?
stackexchange-wordpress
{ "answer_score": 2, "question_score": 0, "tags": "wp cli" }
How to get a value-only flat array from $wpdb->get_results when selecting a single column, without foreach()? My query is: $var = $wpdb->get_results("SELECT field FROM {$wpdb->prefix}table", ARRAY_A); var_dump($var); it returns someting like array(2) { [0]=> array(1) { ["field"]=> string(5) "test1" } [1]=> array(1) { ["field"]=> string(t) "test2" }. I.e. each item is a row with a single name-value pair. What I want is array(2) { [0]=> string(5) "test1" [1]=> string(5) "test2" } Currently I achieve it like this: $var = $wpdb->get_results("SELECT field FROM {$wpdb->prefix}table"); foreach($var as $v_key => $v_val) $var[$v_key] = $v_val['field']; var_dump($var); Is there a shorter way to do this?
Yes, there is. If you want to retrieve just one column from the database table, i.e. all row values for that column, you can use `wpdb::get_col()`. $values = $wpdb->get_col( "SELECT field FROM {$wpdb->prefix}table" ); foreach ( $values as $value ) { // your code }
stackexchange-wordpress
{ "answer_score": 4, "question_score": 1, "tags": "wpdb" }
Updating an imported child theme from the wp-admin UI I have full access to the wp-admin area of a remote WordPress site. I would prefer to work in this UI the whole time and not use FTP. I have successfully imported my custom child theme for an existing parent theme, from within the wp-admin area. My question - From the wp-admin area, can I simply re-upload the same child theme zip package every time I have new changes that needs to be applied to it? Is this a suitable practice? Or will this cause issues?
Uploading a new zip package should work the same way as updating themes or plugins. Please not however that it will only add new files and overwrite existing ones. If you upload a new package without some files (eg. unnecessary CSS or JS), these files will remain on server. So, it is good to take a look from time to time and do some clean up if necessary.
stackexchange-wordpress
{ "answer_score": 0, "question_score": 0, "tags": "child theme" }
Checking a WordPress for OWASP top 10 vulnerabilities I have just made a WordPress plugin and I would like to scan it for OWASP Top 10 vulnerabilities, any resources on how to get started here? Thanks
Try < it has many other testing tools as well, some are free and others paid.
stackexchange-wordpress
{ "answer_score": 1, "question_score": 0, "tags": "plugin development, security" }
Featured Story Shortcode not outputting content So I'm trying to get a shortcode working where it calls the posts in the featured story category but I'm having issue getting it to output even just the title from the post. There's no error on the page. But there's nothing else showing either but white space between the nav and footer. function featured_story() { $args = array( 'posts_per_page' => 5, 'category_name' => 'featured_story' ); $last_5_posts_query = new WP_Query( $args ); while($last_5_posts_query->have_posts()) : $last_5_posts_query->the_post(); $title = get_the_title(); $content .= '<div class="featured-stories">'; $content .= '<h3>' .$title. '</h3>'; endwhile; return $content; } add_shortcode( 'featured-story', 'featured_story' );
First thing : initialize variable $content=''; before the while loop. other than that your code is right. there is something you are doing wrong to use shortcode. you should check this link < and make changes. also if using for custom post type please add post_type argument in $args
stackexchange-wordpress
{ "answer_score": 0, "question_score": 0, "tags": "posts, categories, shortcode" }
How to fix get_the_category function returning incorrect slug? So, I'm having an issue where using the get_the_category function is returning an incorrect slug. My code snippet is as so: <?php $category_detail=get_the_category($post->ID); foreach($category_detail as $cd){?> <li class="list-inline-item"><a href="<?php echo $cd->slug ?>"><?php echo $cd->cat_name; ?></a> </li><?php } The issue is that the category slug doesn't reflect my site's permalink settings, and returns: `"mysite.com/category-name"` and not `"mysite.com/category/category-name".` I am not sure why the category permalink is being truncated, as the category pages work correctly, but this function is outputting them incorrectly, The slug in question here is for regular posts.
The problem, as I could see it, is not with the `get_the_category()` function. Instead, it's the way you output the category archive link: `href="<?php echo $cd->slug ?>"` — you should instead use `get_category_link()` to get the correct URL of the category archive page. Example: <a href="<?php echo esc_url( get_category_link( $cd ) ); ?>">
stackexchange-wordpress
{ "answer_score": 2, "question_score": 0, "tags": "functions, categories, permalinks" }
how can I change the font on Edit Post area (admin dashboard) I need to change the font family on the Edit Post title and post area title. how can I change it? ![enter image description here]( ![need to add this area](
Use admin_head action function admin_css() { ?> <style> //css Here </style> <?php } add_action('admin_head','admin_css');
stackexchange-wordpress
{ "answer_score": 1, "question_score": 0, "tags": "wp admin, title, dashboard" }
Request failed due to an error: (http_request_fail I uploaded the XML file to get back up information such as posts, pages, and media files. either media files, everything came. but for the media files, WordPress gives an error.as a note, the media files have related to the posts and some plugin content. a full error message is Turkish so sorry: İçeri aktarma başarısız Ortam `“1”`: Request failed due to an error: Geçerli bir adres sağlanmadı. (`http_request_failed`) I am giving the XML file: I am good at wp theme and plugin development.SO, is there any coding solution? Are the image files in the XML file in the correct way? < thanks
As a writen links in the xml files, image files such as the files which ends with .jpg extention, were hosted in my ex-hosting.So, now, the image files dont exist now. You can search jpg word in xml files, and you will see links.So, this is a proof what I said above paragraph. So, also the only solution was manually upload again so I solved my problem by hand.
stackexchange-wordpress
{ "answer_score": 0, "question_score": 0, "tags": "import, xml" }
What part of template to edit to remove category name from the top of posts? In the “Twenty Twenty” template I cannot figure out how to remove the display of category name(s) from the top of posts.
There's a filter for that. In a plugin or child theme, add_filter( 'twentytwenty_show_categories_in_entry_header', '__return_false' );
stackexchange-wordpress
{ "answer_score": 1, "question_score": 1, "tags": "posts, templates" }
Wordpress media upload issue could not insert attachment into the database Could not insert attachment into the database. When ever I try to upload new images from WordPress media it shows me above error. Please help me why wp database shows this error.
Try the following solutins: 1. First of all check your WP database size and check whether the size is full according to your hosting provider's requirement/rule. 2. Second option, add this line into your **wp-config.php** : define('WP_MEMORY_LIMIT', '256M'); Also if you have access to **php.ini** (or php[version number].ini) file on your server, try to add this line: memory_limit 512M 3. By default, some database configs have a collation or charset that doesn't allow special character. Check whether the file name of the image you're trying to upload is having any special characters. If so, delete them and use only alphanumeric. Then retry. 4. Also, please check your folder permission. Read more about it on < Hope it helps.
stackexchange-wordpress
{ "answer_score": 0, "question_score": 0, "tags": "uploads, media, media library" }
how to retrieve the image title for image Post Format Hope everyone is having a good day. in WordPress Codex Post Format the image post format is defined as > **image** – A single image. The first tag in the post could be considered the image. Alternatively, if the post consists only of a URL, that will be the image URL and the title of the post (post_title) will be the title attribute for the image. Now i need to know about what title attribute they are talking about in the above definition of image post format and how to retrieve that title through php as all the data is coming from the_content() function, anyone has any idea? i have researched online and there is literally no issue about this one.
So first off, I hope you're aware that the quote there is a _guideline_ on how should a post of the `image` format be displayed to the user, and the thing about the title attribute applies only to posts where the format is `image` and that the post content is the image URL only, e.g. ` > what title attribute they are talking about It's the `title` attribute of the `<img>` tag, and the attribute value should be set to the post title. > how to retrieve that title through PHP There are some functions you can choose from such as `get_post_field()`, `get_the_title()` and `the_title_attribute()`. So for example, your `<img>` can be generated like so: <img src="<?php echo esc_url( get_post_field( 'post_content' ) ); ?>" title="<?php the_title_attribute(); ?>">
stackexchange-wordpress
{ "answer_score": 1, "question_score": 0, "tags": "theme development, images, post formats" }
how to serialize() mysql update data Hi I want to make the serialized reading value 1 or 0 in mysql, how can I do example code $query = $wpdb->get_results('select * from wp_options where option_id = 96'); $dizi = unserialize($query[0]->option_value); // echo $dizi['subscriber']['capabilities']['read']; //print_r($dizi); if(array_key_exists('read', $dizi['subscriber']['capabilities'])){ echo $dizi['subscriber']['capabilities']['read'] = 0; } exit;
You should not use raw SQL to modify roles and capabilities, it is very bad practice, and unnecessary. Instead, use the roles API, e.g. $role = get_role( 'subscriber' ); $role->add_cap( 'read' ); Or to add it to a specific user: $user = new WP_User( $user_id ); $user->add_cap( 'read' ); Likewise you can remove a capability from a role: $role = get_role( 'subscriber' ); $role->remove_cap( 'read' );
stackexchange-wordpress
{ "answer_score": 1, "question_score": 0, "tags": "php" }
How to make a list of companies' information and display them to user, using custom post types and a custom taxonomy? I need to add a list of companies' information to my website and I want to display the list in a page. Then by clicking on each company, user can see more information about that company in its individual post. What is the right approach for doing this? I researched about custom post types and custom fields. But they seem to be not right for me. Do I have to build a post for each company? They are more than a hundred. Is there a more speedy way to do this? P.S The companies has identical fields. Each company has a name, description, etc and also has a few photos.
Custom post types and taxonomies are the appropriate method of doing this. It sounds like you've already identified the appropriate taxonomies and CPT: * A `company` post type * A `company_type` taxonomy `register_post_type` and `register_taxonomy` can do this for you. Don't forget to re-save permalinks if you use those functions or change their parameters. After doing this, new sections will appear in the Admin sidemenu, as well as frontend listings, and theme templates. Further Reading * < * < * < * < * < Generators: * < * <
stackexchange-wordpress
{ "answer_score": 0, "question_score": 0, "tags": "plugins, custom post types, custom taxonomy" }
Remove taxonomies using register_post_type_args The theme I'm using is adding taxonomies to CPT using `register_post_type` and `'taxonomies' => array('portfolio-cat')` as one of the arguments. I need to remove that particular taxonomy using `register_post_type_args`. I have tried with: add_filter( 'register_post_type_args', 'change_portfolio_post_type_args', 10, 2 ); function change_portfolio_post_type_args( $args, $post_type ) { if ( 'portfolio' === $post_type ) { unset($args['taxonomies']); // Not working unset($args['taxonomies'][0]); // Not working $args['taxonomies'] = array(); // Not working $args['taxonomies'] = array('category'); // It justs add another taxonomy } return $args; } How can I remove it, without touching theme core files?
Did you try this? Here: `unregister_taxonomy_for_object_type()` Read more: < function unregister_portfolio_cat_for_portfolio() { unregister_taxonomy_for_object_type( 'portfolio-cat', 'portfolio' ); } add_action( 'init', 'unregister_portfolio_cat_for_portfolio' );
stackexchange-wordpress
{ "answer_score": 1, "question_score": 0, "tags": "custom post types, custom taxonomy, post type" }
Custom Page out of Wp Theme i have this website running in WP and I had to create a feature to generate pages automatically and I did it through a separate WP backend, which creates the .php pages within the root of the site. When I call **domain/slug-of-page.php** everything is ok. But when I call the page without the extension (.php) the WP understands that it is an invalid url (404 error) because there is no page in the WP with that name. I tried to insert the page created in the `wp_posts` table but when calling the page it loads the WP theme ... I don't want it to load the theme. Is there a way to make the url friendly (without the extension) and not handled by the WP handler? Thanks for every help.
try this, wordpress has custom page templates. Creating Custom Page Templates for Global Use
stackexchange-wordpress
{ "answer_score": 0, "question_score": 0, "tags": "custom post types" }
shortcode with conditional results if logged in I need some help, I am learning php through wordpress, so I don't really know the php basic and don't really know wordpress either. so I have this shortcode function: function links( $atts, $content = null ){ $args = shortcode_atts( array( 's' => '', 'l' => '', ), $atts); $api = file_get_contents('API URL'.$args['l']); $result1 = '<a href="'. $api .'">'. $args['s'] .'</a>'; $result2 = '<a href="'. $args['l'] .'">'. $args['s'] .'</a>'; return THIS IS I NEED THE IF LOGGED IN SHOWS $result2 AND THE OTHERWISE } add_shortcode ('link', 'links'); the shortcode is already written in custom meta box group text area from foreach. [link s="Google" l=" I write this in `single.php` echo do_shortcode($linkx['link_box']); thank you in advance.
Use `is_user_logged_in()` in the logic to decide what to return. See < I assume `$linkx['link_box']` contains the shortcode.
stackexchange-wordpress
{ "answer_score": 1, "question_score": 0, "tags": "shortcode" }
How to display get_post_type() translated? In my content-search.php template file I did something like this: <tr id="post-<?php the_ID(); ?>" <?php post_class(); ?>> <td><?php the_post_thumbnail( 'thumbnail' ); ?></td> <td style="padding: 15px;"> <?php echo '<h6>' . ucfirst( get_post_type( get_the_ID() ) ) . '</h6>'; the_title( sprintf( '<h5><a href="%s" rel="bookmark">', esc_url( get_permalink() ) ), '</a></h5>' ); echo '<p>' . get_the_excerpt() . '</p>'; ?> </td> </tr> ![enter image description here]( It returns posts image, post type name in English, title and excerpt on search results page. Posts, pages or another custom post types by searched term. I need to display post type name translated into another language.
Based on a previous Q&A, How to get current get_post_types name?, you could use `get_post_type_object()` to get the whole post type object, which will have the translated name in it. $post_type_object = get_post_type_object(get_post_type()); if ( $post_type_object ) { echo esc_html( $post_type_object->labels->singular_name ); }
stackexchange-wordpress
{ "answer_score": 1, "question_score": 1, "tags": "translation, post type" }
Upload error on localhost (at minimum, not yet tested online) uploading a picture on localhost I keep receiving following error: > Post-processing of the image failed likely because the server is busy or does not have enough resources. stopping any upload, even the file is relatively small, few kb, 1290x720, or max 1980x1020 or similar. tried the way to modify app/theme/theme_name/app/setup.php by adding add_filter( ‘wp_image_editors’, function() { return array( ‘WP_Image_Editor_GD’ ); } ); with no success. still having same issue. created a plugin with: add_filter( 'big_image_size_threshold', '__return_false' ); but still nothing (MEDIA settings are capped to 9999 per each dimension) any basic config am I missing? ty and best! :smiley: EDIT: PS: no way with the “official” plugin as well…
the issue was connected to a standard too strict php.ini configuration. to solve this, one has to update php.ini file setting to an higher > upload_max_file_size = 2M // something more value.
stackexchange-wordpress
{ "answer_score": 0, "question_score": 0, "tags": "images, uploads, admin, media" }
How to Update post_modified of all wordpress post i want to update all my wordpress post modified date and time to a specific date and time, i have a code to update it base on the id, but i want one to update all the row at once without putting the id of the posts . $sql = "UPDATE Zulu_posts SET post_modified='2020-11-17 16:06:00' WHERE id=2"; if ($conn->query($sql) === TRUE) { echo "Record updated successfully"; } else { echo "Error updating record: " . $conn->error; } $conn->close();
You can use a generalized update query. As always, when dealing with databases **take a backup first**. With that out of the way, your query should look something like: BEGIN; -- Start a transaction UPDATE wp_posts SET post_modified = <Your new date> AND post_modified_gmt = <Your new date in GMT>; SELECT * FROM wp_posts LIMIT 10 ORDER BY post_date DESC; -- See the 10 most recently authored posts, make sure their post_modified and post_modified_gmt looks good COMMIT; -- Commit the changes to the database or ROLLBACK; -- If things don't look right. **Edit** : in your case, if you do this in PHP, **definitely** take a backup, and then make `$sql` everything above except for the lines with `BEGIN`, `COMMIT`, and `ROLLBACK`, though I'd recommend doing this in the command line or a GUI/web interface.
stackexchange-wordpress
{ "answer_score": 0, "question_score": 0, "tags": "php, sql" }
How to align a single Gutenberg block button in WP 5.5.3? With some WP update, the single block button suddenly disappeared from Gutenberg blocks. Now, we only have a block 'Buttons' element (don't know why actually. I reckon' that >80 per cent of all uses are single button scenarios...). So, how can I adjust alignment from within the editor, if I have only a single button? Say, I need to center the button. Can't find any alignment options with the element anymore either, as people suggested here.
1. select the entire 'buttons' block ![select the entire 'buttons' block by to block toolbar, list view, choose buttons]( 2. once the entire buttons block is selected, ![go to the justify toolbar icon, and select how to center]( For future reference, the wordpress.com button article is usually current although it is currently out of date at the moment.
stackexchange-wordpress
{ "answer_score": 3, "question_score": 1, "tags": "block editor, buttons" }
Performance of several get_option() calls I am currently working on my first WordPress plugin. To save and output certain settings I use the native Settings API. Now the question arises, how performant are several calls of the get_option() function. Since I work object-oriented I use a function which returns the options: private function get_settings() { $styles = get_option("style_settings"); return $styles; } Every time I need one or more values from the options array, I now call this function. Is it better to assign the options in the constructor to a variable or does it not matter for the performance?
If you check the implementation of `get_option()` you'll see that in line 168 it calls `wp_cache_get()` like so: $value = wp_cache_get( $option, 'options' ); This means multiple calls to `get_option("style_settings")` within the same PHP execution will be served from cache. There is no need to re-invent this, as you might break other functionality with it. (There are various filters and hooks in the `get_option()` call with which plugins may interfere with this. Unless you have specific reasons, you usually want these to be executed.)
stackexchange-wordpress
{ "answer_score": 2, "question_score": 2, "tags": "plugin development, options, settings api, plugin options" }
why wp_enqueue_scripts() not working? here is code function custom_theme_script(){ wp_register_style('bootstrap', get_template_directory_uri() . '/css/bootstrap.css' ); wp_enqueue_style('bootstrap'); wp_register_style('style', get_template_directory_uri() . '/css/style.css'); wp_enqueue_style('style'); wp_deregister_script( 'jquery' ); wp_enqueue_script('bootstrap.min', get_template_directory_uri() . '/js/bootstrap.min.js', array(), '3.5.1', true ); } add_action('wp_enqueue_scripts', 'custom_theme_script');` this is screenshot of head tag ![enter image description here]( what is missing in header.php and functions.php file
Hey bro Use this code **get_stylesheet_directory_uri** function custom_theme_script(){ wp_register_style('bootstrap', get_stylesheet_directory_uri.() .'/css/bootstrap.css' ); wp_enqueue_style('bootstrap'); wp_register_style('style', get_stylesheet_directory_uri() . '/css/style.css'); wp_enqueue_style('style'); wp_deregister_script( 'jquery' ); wp_enqueue_script('bootstrap.min', get_template_directory_uri() . '/js/bootstrap.min.js', array(), '3.5.1', true ); } add_action('wp_enqueue_scripts', 'custom_theme_script'); `
stackexchange-wordpress
{ "answer_score": 1, "question_score": 0, "tags": "wp enqueue script" }
how to change image of jquery slider plugin I want to put the "swiper slider" in my front page. I can set this plugin work with html, js, css. But, I wonder how to change images of this slider in admin. when I use jquery plugin, I want to change image of slide in admin area. Can you give me some tips to change images in admin that is tagged in html.
There are multiple ways to make the slider dynamic. If you use the Gutenberg editor, you can add new style to the Gallery like this: register_block_style( 'core/gallery', [ 'name' => 'swiper', 'label' => __( 'Swiper Slider' ), ] ); Then create gallery and choose the Swiper style. It will add an extra class `is-style-swiper` to the gallery. Target that with CSS and JS. If you use ACF (Advanced Custom Fields), then it's even easier to change the HTML markup to fit whatever Swiper needs.
stackexchange-wordpress
{ "answer_score": 1, "question_score": 0, "tags": "plugin development, images, slideshow" }
display most active user sort by comment count [Solved] i'm using "WP_User_Query" to displaying the most active user orderby = "post_count" in front and It works fine, now i want to display the most active user based on comment count in front i will be appreciate it if anyone could help me on this.
you can use this $user = new wp_user(get_current_user_id()); function commentCount() { global $user; global $wpdb; $count = $wpdb->get_var('SELECT COUNT(comment_ID) FROM ' . $wpdb->comments. ' WHERE comment_author_email = "' . $user->data->user_email . '" and comment_approved = 1'); return $count; } echo ''; echo commentCount();
stackexchange-wordpress
{ "answer_score": 0, "question_score": 0, "tags": "php" }
Is there any way to use @wordpress/i18n for <5.0? I'm looking to make use of translation strings inside my JS files and unfortunately, I've read that `@wordpress/i18n` doesn't work <5.0. Are there any tools/libraries that help me with this?
**No. That library requires a newer version of WordPress.** If you want to use that library then you need to update your version of WordPress to a more recent version.
stackexchange-wordpress
{ "answer_score": 3, "question_score": 0, "tags": "translation" }
Please select a file error I am facing `Please select a file` error while trying to upload a plugin. My `php.ini` settings are like below * upload_max_filesize = 20000 * max_file_uploads = 200 * max_execution_time = 300 * max_input_time = 600 * memory_limit = 12800 * post_max_size = 8000 My WordPress Version 5.5.3 ![enter image description here](
I guess it is a hosting issue. Contact your hosting company support. If it is in the localhost server then there may have a permission issue ...
stackexchange-wordpress
{ "answer_score": 2, "question_score": 0, "tags": "plugins, uploads, installation" }
Some WordPress Posts are automatically becoming comments on other Posts This seems like a weird issue. I have published multiple posts on one of my websites. Sometimes, another post on my website (Post C) appears as comment under some other post (Post A). The content of the comment on (Post A) will be some content of (Post C) surrounded by ellipsis. The author of the comment is mentioned as the title of Post C and it links back to Post C. The IP addresses for the comments may or may not be different. Most of them are from Texas, USA. The gravatar of the comment seems to link to an image trackback.png. How can I stop these comments from appearing on the website? Thanks.
This is called pingback. Whenever you link another post, that post will be notified as a comment. I personally don't like this feature. You can disable it in Settings > Discussion > untick "Allow link notifications from other blogs". I think this setting will only apply to new posts, so you also need to disable them using Quick Edit. In your post list > tick all posts > bulk action edit > set Pings to "Do not allow"
stackexchange-wordpress
{ "answer_score": 1, "question_score": 0, "tags": "plugins, comments" }
register/login api I have been looking all over google and all I can find is fairly old plugins that appear outdated in assisting with an API registration/login. Basically, I have a mobile app that needs to get data from the WordPress backend via the API. I want users to be able to register on the app and to obviously log in. Is there support out of the box for this in WordPress or do you need to create a custom route etc? I looked here: < and I tried to use postman to post username, email and password to this endpoint < But it gives me an error. Any advice on how to do this would be greatly appreciated.
> Is there support out of the box for this in WordPress or do you need to create a custom route etc? No, there is no endpoint for user login and registration. You would need to install an authentication plugin designed for remote auth such as the OAuth2 plugin, or wait until 5.6 adds application passwords. No endpoint exists for user registration. > and I tried to use postman to post username, email and password to this endpoint That endpoint can be used to create new users but only if made as an authenticated request from a user that can do that, aka the add new user button in the backend. It can't be used for registration.
stackexchange-wordpress
{ "answer_score": 0, "question_score": 0, "tags": "rest api, api, authentication, wp api" }
Get taxonomy name for the current post I am trying to get the name for a custom taxonomy assigned to the current post and in my template I have: $countries = get_terms( 'country', array('hide_empty' => false,)); $fcountry = $countries[0]->slug; However this returns the first item in the `$countries` array, instead of the term that is assigned to the current post.
You should no longer use the _legacy_ function parameter format. Instead, as the documentation says, use the `get_terms( $args )` format: > Since 4.5.0, taxonomies should be passed via the ‘taxonomy’ argument in the `$args` array: > > > $terms = get_terms( array( > 'taxonomy' => 'post_tag', > 'hide_empty' => false, > ) ); > And as for getting only the terms assigned to the current or a specific post, you can either use the `object_ids` parameter with `get_terms()`, or simply use `get_the_terms()`. So for examples: $post_id = get_the_ID(); $countries = get_terms( array( 'taxonomy' => 'country', 'object_ids' => $post_id, // set the object_ids ) ); // Or just use get_the_terms(): $countries = get_the_terms( $post_id, 'country' );
stackexchange-wordpress
{ "answer_score": 1, "question_score": 0, "tags": "custom taxonomy, taxonomy" }
Get the automatic excerpt from a page created with gutenberg The problem I have is im not getting the automatic excerpt (the_excerpt()) when I create a post with gutenberg blocks, If I put an image or something before the text it looks like gutenberg does not undestand it, if I put just text is ok but If I add images or a different block that is not text it is empty, is there a way to detect the first block of text in a post and use it like excerpt. Thank you.
You can hook the `get_the_excerpt` filter with `parse_blocks` to extract the content of your post. add_filter( 'get_the_excerpt', 'se378694_default_excerpt', 10, 2 ); function se378694_default_excerpt( string $post_excerpt, WP_Post $post ):string { if ( empty( $post_excerpt ) ) { $blocks = parse_blocks( $post->post_content ); // check if the first block matches the type of content you want for your excerpt if ( ... ) { $post_excerpt = render_block( $blocks[ 0 ] ); } } } You can use render_block() if you want to get the final content of any block in your post content. And parse_blocks() to convert the post content (string) into an array of blocks.
stackexchange-wordpress
{ "answer_score": 1, "question_score": 0, "tags": "excerpt" }
Nav Menu: Theme Location not working Why do my created Menus on the WordPress Admin dashboard appear in `customtemplate.php` DESPITE not defining it the correct `'theme_location'`? It will show in that location EVEN if the created menu in the WordPress Admin dashboard is not set to show in any location. It only hides if the following if check is tested. Why? if(has_nav_menu('menu-ID1')) **Functions.php** register_nav_menus( array( 'menu-ID1' => __( 'MenuName', 'blabla' ), ) ); **customtemplate.php** //Still displays even though the registered menu-ID1 is not used wp_nav_menu(['theme_location' => 'randomname']);
I'm guessing your menu contains only Pages (posts of the `page` type) on your site? But nonetheless, with `wp_nav_menu()`, if you specify a `theme_location` that doesn't exist or contains no menu (i.e. no menus assigned to that location), then the `fallback_cb` arg (which defaults to `wp_page_menu()`) will determine what is displayed. So if you want the function to display the menu only if it's assigned to the specified theme location, you can do the `has_nav_menu()` check: if ( has_nav_menu( 'menu-ID1' ) ) { wp_nav_menu( 'theme_location=menu-ID1' ); } or set the `fallback_cb` to an empty string: wp_nav_menu( array( 'theme_location' => 'menu-ID1', 'fallback_cb' => '', ) ); // or you may pass the function args as a query string: wp_nav_menu( 'theme_location=menu-ID1&fallback_cb=' );
stackexchange-wordpress
{ "answer_score": 0, "question_score": 0, "tags": "menus, navigation" }
Adding author option to [products] woocommerce shortcode I am trying to modify the [products] shortcode usage: < What I am looking was passing the author id from short code e.g [products author=2] to the query. With the reference of: < But the sample was a true/false parameter to trigger the $query_args change, seems it's not exactly my goal. And the function below is the only part I can put into use. function htdat_woocommerce_shortcode_products_query( $query_args, $attributes ) { $query_args = array( //Receive the id//'author' => '1', 'post_status' => 'publish', 'post_type' => 'product', 'post_per_page' => 12, ); return $query_args; } add_filter( 'woocommerce_shortcode_products_query', 'htdat_woocommerce_shortcode_products_query', 10, 2 ); If anyone could help, thank you.
Try this: function htdat_shortcode_atts_products( $out, $pairs, $atts, $shortcode ) { if ( isset ( $atts['author'] ) ) $out['author'] = $atts['author']; return $out; } add_filter('shortcode_atts_products', 'htdat_shortcode_atts_products', 10, 4); function htdat_woocommerce_shortcode_products_query( $query_args, $attributes ) { if ( isset( $attributes['author'] ) ) $query_args['author'] = $attributes['author']; return $query_args; } add_filter( 'woocommerce_shortcode_products_query', 'htdat_woocommerce_shortcode_products_query', 10, 2 );
stackexchange-wordpress
{ "answer_score": 1, "question_score": 0, "tags": "woocommerce offtopic, shortcode, author" }
Which HTTP headers to use for subdomain <iframe> embedding? I have a Wordpress site hosted on LightSail (which uses bitnami). The domain is ` On a subdomain ` I have another server running. On this server, I want to embed a page from the main domain ` Currently, I am getting errors that permission is denied. I have updated the htaccess file like so: Header set X-Frame-Options "ALLOW-FROM Header set Content-Security-Policy "frame-ancestors 'self' https: *.example.com" Header set Referrer-Policy "strict-origin-when-cross-origin" But the headers don't seem to updating or allowing any iframe embeds. I'm not very well-versed on HTTP Headers so apologies if this is a rather silly question. Thanks!
I was able to figure out that because Lightsail uses a Bitnami deployment of Wordpress, Bitnami overrides the `.htaccess` file. Instead you have to update the `/opt/bitnami/apache2/conf/httpd.conf` file by adding the following content: <IfModule headers_module> <IfVersion >= 2.4.7 > Header always setifempty X-Frame-Options ALLOW-FROM </IfVersion> <IfVersion < 2.4.7 > Header always merge X-Frame-Options ALLOW-FROM </IfVersion> </IfModule> Reference: <
stackexchange-wordpress
{ "answer_score": 1, "question_score": 2, "tags": "wp admin, htaccess, https, embed, iframe" }
Wordpress rewrites my link with custom URL scheme to http(s) I have a page that only users of my native iOS app will find, which should open the app. This works (on any other HTML page anyway) by linking to "myapp://path/inside/app". Wordpress keeps "fixing" this to " which doesn't work of course. I didn't find a setting to stop it from doing this. Is this possible?
I created this plugin to address my problem: < At the moment it only works for my apps, pull requests welcome!
stackexchange-wordpress
{ "answer_score": 0, "question_score": 0, "tags": "urls, links" }
Restricting shortcode for users anyway to block any user /role(except the admin) to use shortcode? i want to keep some specific shortcode secret. if somehow users come to know, they cant use it. if only admin writes the shortcode it will make changes to site, but if someone else write the shortcode it will be taken as a simple text.
i think this might work with you function myshortcode(){ $user = wp_get_current_user(); if ( !in_array( 'author', (array) $user->roles ) ) { //Run shortcode } } add_shortcode('myshortcode','myshortcode');
stackexchange-wordpress
{ "answer_score": 0, "question_score": 0, "tags": "shortcode, capabilities" }
Create a custom display order in the main menu I have main menu which displays two types of links: CPT and Subcategory. I create the menu with a custom request: I retrieve the Custom Post Type then the sub-categories of the main category in Alphabetical order : Category A: - Product a - Product b - sub category a - sub category b ... But, my client wants a custom display example: Category A: sub category a - Product b - Product a - sub category b ... I thought about creating a Drag Drop solution ... but how to implement it
You can use this plugin for sorting custom post type or taxonomy
stackexchange-wordpress
{ "answer_score": 1, "question_score": 1, "tags": "plugin development, wp query" }
Checking if looped item has a parent inside a shortcode all I want is to check if the custom post item in the loop has a parent. I am using this inside a shortcode. I could not find how to access the property from inside the loop. Thank you my dears $q = new WP_Query(array( 'post_type' => 'my_custom_post_type', 'posts_per_page' => 5, 'category' => '', )); while ($q->have_posts()) { $q->the_post(); ... <- Check if the loop item has a parent } wp_reset_postdata();
The `WP_Post` class has an attribute `post_parent` that you can use for this. while ($q->have_posts()) { $q->the_post(); $post = get_post(); if (!empty($post->post_parent)) { // do something different } }
stackexchange-wordpress
{ "answer_score": 2, "question_score": 0, "tags": "custom post types, shortcode" }
Add button to Block toolbar: toggleFormat is undefined I'm try to add a custom button to the toolbar for paragraph blocks. I followed the steps reproduced in this great tutorial: The button is correctly showing up and every piece of code in that project is working good. I have some trouble to get the content updated inside the editor when the button is clicked. I tried to follow this guidelines: < but I get a console error saying that the method toggleFormat is undefined. I share this github: **Gutenberg Buttons** , if someone can help me to fix the issue. Thank you
Now I can see what the problem is. You are not using the `onChange` properly. It comes from the `props` of the edit component: ![]( Here you have a complete example that works: registerFormatType( 'nelio/keyboard', { title: __( 'Key', 'nelio' ), tagName: 'kbd', className: null, edit: ( { value, onChange } ) => ( <RichTextToolbarButton icon="editor-removeformatting" title={ __( 'Key', 'nelio' ) } onClick={ () => onChange( toggleFormat( value, { type: 'nelio/keyboard' } ) ) } /> ), } );
stackexchange-wordpress
{ "answer_score": 1, "question_score": 0, "tags": "block editor" }
Where do I have to put an image in order to use in a Custom HTML img? I am trying to use custom HTML in a widget and I can't make an `img` tag to work because I have no idea where to store the image. Where does one store an image inside a WordPress website ? And not by "Upload Image", no. By using FTP. Where exactly do I have to store images so that I can link them to an `img` tag.
To get img url first upload it to media library, then click on the img you want to use, and see the full url in the img details. see photo attached with a circle around the url of the img. ![img uploaded to media](
stackexchange-wordpress
{ "answer_score": 0, "question_score": 0, "tags": "html" }
How to edit title on Edit post pages? The `<title`> tag in pages for post edit is `Edit Post < Site name — WordPress`. I want to change it to `Edit Post < Site name – The title of the post in editing`. Is this possible? Where can I locate the header of this page? Apparently it cannot be in the theme. ![enter image description here](
Add this code instead on your functions.php, this will change the post and product title to the post or product that is being edit: add_filter('admin_title', 'my_admin_title', 10, 2); function my_admin_title($admin_title, $title) { global $post, $action; if ( isset($post->post_title) and $action == 'edit' ){ return 'Edit < '.$post->post_title.' - '.get_bloginfo('name'); } else { return $title .' - ' .get_bloginfo('name'); } }
stackexchange-wordpress
{ "answer_score": 2, "question_score": 1, "tags": "title, post editor" }
Sanitizing file & directory form input I'm looking to sanitize admin form input for update_option. The input is for a directory path and file name. The input will look like this: /directory/subdirectory/ and /thisfile.min.js So far, every sanitize I've tried strips out the forward slashes. Any suggestions?
The function that you would want to use is `sanitize_text_field()` which among other things, strips all HTML tags, and remove line breaks, tabs and extra white space. // This worked fine for me - I got /directory/subdirectory/ $value = sanitize_text_field( '/directory/subdirectory/' ); // And so does this one - I got /thisfile.min.js $value = sanitize_text_field( '/thisfile.min.js' ); // Even with an actual form input (e.g. <input name="my_field">), // the function worked just fine (using the same data as above). $value = sanitize_text_field( $_POST['my_field'] ); So have you already tried that function and are you sure it stripped the `/`? How about the other similar functions listed here?
stackexchange-wordpress
{ "answer_score": 1, "question_score": 0, "tags": "plugins, plugin development" }
How to make applyFilters function return false via functions.php So I have a following code inside the plugin: if( window.wp.hooks.applyFilters( 'filtername', true, $(this) ) ) { //do something } how can I make above statement always false without editing plugin files but using functions.php instead? I'm not sure if I understand applyfilters correctly but I've tried: function filtername() { return false; } add_filter( 'filtername', 'filtername', 10, 3 ); but it didn't work. What would be propper way to do it? Can someone please explain.
JS hooks don't do server-side calls to retrieve PHP declared hooks. wp.hooks.addFilter( 'hookName', 'namespace', () => { return false; }, 10 )
stackexchange-wordpress
{ "answer_score": 3, "question_score": 2, "tags": "functions, filters" }
How to sort by number I have to sort my results by number: <ul> <?php $productTerms = get_terms('prezzoceste', array('hide_empty' => 0, 'orderby' => 'ASC', 'meta_type' => 'NUMERIC', )); foreach($productTerms as $productTerm) : ?> <li> <i class="fas fa-circle"></i> <a href="<?php echo get_term_link( $productTerm->slug, $productTerm->taxonomy ); ?>"><?php echo $productTerm->name; ?> <span>(<?php echo $productTerm->count; ?>)</span></a> </li> <?php endforeach; ?> </ul> ![enter image description here](
You are using pre 4.5.0 code which will eventually be depricated. Try this. $productTerms = get_terms( array( 'taxonomy' => 'prezzoceste', 'hide_empty' => false, 'orderby' => 'ASC', 'meta_key' => '_price', //The price Meta Key 'orderby' => 'meta_value_num', ) ); Check this for more accepted arguments.
stackexchange-wordpress
{ "answer_score": 1, "question_score": 0, "tags": "sort" }
email alert for product availability I want to give the user the possibility to click a button when the product stock is 0. the idea is to send an email to the user as soon has the product has been restablished. I can make this farely easy by doing a table, writting a function and sending and email, more or less like this, right. However I would like to know if wordpress has any function or funcionallity to do exactly this.
this called waitlist you can use this free plugin
stackexchange-wordpress
{ "answer_score": 1, "question_score": 0, "tags": "php, woocommerce offtopic, mysql" }
Create an if is_page statement based on parent page I am trying to show something in a template based on what page is showing. This is working fine until I want to show a part of the template based on whether the parent post page slug is 'courses'. So the page url ends in '.com/courses/course-1' so I want specific code to show for all posts where the post parent slug is 'courses' I have tried the following: global $post; $post_data = get_post($post->post_parent); <?php if ( is_page( array( 'learn', 'profile') ) || ($post_data->post_parent == 'courses') ) { ?> THINGS GO HERE <?php } ?> but for some reason once I add the code `|| ($post_data->post_parent == 'courses')` the if statement is then ignored on the template. The result is that even if a page not listed in the array, the 'THINGS GO HERE' is generated anyway. What am I doing wrong?
**Hey ! This should work.** $current_url = home_url( $wp->request ); if (strpos($current_url,'courses') !== false) { //Do Something } else { //Do Something }
stackexchange-wordpress
{ "answer_score": 0, "question_score": 1, "tags": "php" }
How to safely remove the footer (twentytwenty) Is it safe to remove get_footer(); from the index.php ? I don't need any footer.
Its not safe and not recommended. Thats action that read all Javascripts, CSS from other plugins or theme. Hide your footer with css or theme option. #footer,footer{display:none!important}
stackexchange-wordpress
{ "answer_score": 3, "question_score": 1, "tags": "php, footer" }
How to disable WordPress from automatically changing "x" to multiplication symbol "×" when typing numbers that also contain an "x" between them? I simply want to be able type, for instance, "7x12 house design". WordPress, however, automatically changes x (alphabet) to × (<\- this is a multiplication symbol special character): "7×12 house design". How can I disable this?
This is part of wptexturize, which includes a number of other transforms such as generating en- and em-dash symbols, ellipses and curly quotes. (Here's the specific code for this, known as 'multiplication symbol' in the documentation but 'times' in the code.) You can disable wptexturize completely with add_filter( 'run_wptexturize', '__return_false' ); but there's no built-in way to disable just this one wptexturize rule.
stackexchange-wordpress
{ "answer_score": 0, "question_score": 0, "tags": "posts" }
HTML comment cause issue in functions.php script root I noticed HTML comment tag `<!-- -->` will cause issue on themes _functions.php_ script if it is in the root of script(not inside a function). I was working on my themes functions.php to add some _Easy Digital Downloads_ action/filter, which i realized purchase button will continue to loading and doesnt add product to basket. after clearing an html comment that was in the root of script,issue solved. i need to know whats wrong with having HTML comment in functions.php root ? (BTW my wp site is hosted on a cpanel shared host)
The `functions.php` is loaded before WordPress has sent the HTTP response headers. If you have raw HTML content in that file, even a HTML comment, then that will be sent immediately, triggering PHP's built-in HTTP headers. Now, WordPress doesn't know about this and tries to send the headers as usual. And that will cause an error message like "Headers already sent …". This message comes with information about the file and line that created the first output, so it's rather easy to debug. Long story short: Don't create raw output in the `functions.php`, use template files for that.
stackexchange-wordpress
{ "answer_score": 0, "question_score": 0, "tags": "php, functions, html" }
filter hook to load a different post/page on current post/page I have 2 pages: 1. `/contact` 2. `/contact-team` The `/contact` page has a popup and on user selection, the page must reload but with the contents of `/contact-team`. Is there a filter hook which can load a different post altogether after the URL has been generated? I have tried the `pre_get_posts` to set the post ID but it gets redirected to that ID. I want the page loaded to be `/contact` but the content should be from `/contact-team`. Any ideas?
You can use the `request` hook to change the loaded page for the same URL: add_filter( 'request', function( $request ){ //Replace this with custom logic to determine if the user should see the contact-team page $load_team_contact = true; if( $load_team_contact && isset( $request['pagename'] ) && 'contact' == $request['pagename'] ){ $request['pagename'] = 'contact-team'; } return $request; } ); You just need to determine if the user should see the contact team page which would vary depending on your setup.
stackexchange-wordpress
{ "answer_score": 1, "question_score": 0, "tags": "filters, hooks" }