INSTRUCTION
stringlengths
11
999
RESPONSE
stringlengths
0
999
SOURCE
stringlengths
16
38
METADATA
dict
How do i disable or Remove the Native Wordpress Video Player? Any idea on how I can totally disable or entirely remove the default/Native Wordpress video player?
welcome aboard. WordPress uses Media Elements JS for default video/audio player. You can disable this scripts with this code. Please add this code to **your theme's** `functions.php` function deregister_media_elements(){ wp_deregister_script('wp-mediaelement'); wp_deregister_style('wp-mediaelement'); } add_action('wp_enqueue_scripts','deregister_media_elements'); PS. This code de-register mediaelements.js from all WordPress (with your current theme).
stackexchange-wordpress
{ "answer_score": 7, "question_score": 5, "tags": "video player" }
Is there a way to dynamically get to your uploads folder? I have a locally hosted site that uses bootstrap to create a carousel with pictures from the upload folder. I currently have the bootstrap markup using the source of the pictures, but I fear when I load the site to a live server those links are not going to work anymore? Is there a dynamic way to get to the upload folder, maybe with the use of an inbuilt WordPress function, so that the path to the pictures that are used in the carousel always work?
Take a look at `wp_upload_dir` here < $upload_dir = wp_upload_dir(); var_dump( $upload_dir ); /* $upload_dir will comprise of the following return values: 'path' - (string) Base directory and subdirectory or full path to upload directory. 'url' - (string) Base URL and subdirectory or absolute URL to upload directory. 'subdir' - (string) Subdirectory if uploads use year/month folders option is on. 'basedir' - (string) Path without subdir. 'baseurl' - (string) URL path without subdir. 'error' - (string|false) False or error message. */
stackexchange-wordpress
{ "answer_score": 1, "question_score": 1, "tags": "customization, images" }
How can get the last post date of the user? I want to get the last post date was written by the user and here's the code that I have made but it's not working: function get_user_last_post_date( $user_id ) { $args = array( 'post_author' => $user_id, 'post_type' => 'any', 'post_status' => 'publish', 'posts_per_page' => 1, 'order' => 'DESC', 'orderby ' => 'post_date' ); $latest_posts = new WP_Query( $args ); $last_date = ''; if ( $latest_posts->have_posts() ) { $last_date = $latest_posts; } return $last_date; }
In your sample code the `$latest_posts` is an instance of WP_Query class. If you want to get the latest post's date, you should do this: $latest_posts = new WP_Query( $args ); $last_date = ''; if ( $latest_posts->have_posts() ) { $latest_posts->the_post(); $last_date = get_the_date(); } return $last_date;
stackexchange-wordpress
{ "answer_score": 0, "question_score": 0, "tags": "posts, users, date" }
How to add a link to an external website in the description of a customizer control (with Kirki)? I'm building a Wordpress theme and I use the Kirki Customizer framework to add controls and settings to the customiser. I added a description to some controls, using the following code: 'description' => esc_html__( 'Description here', 'kirki' ), Now I want to add a link in the description to an external website. I already tried inserting HTML, but that doesn't work; it just did just output the flat HTML code. It probably has sth to do with the esc_html__() thing, but I already searched on the internet and couldn't find a solution for this. Please enlighten me if you have a solution! Thanks a lot ;)
`esc_html__` is a translation API, specifically it's equivalent to this: $var = esc_html( __( ... ) ); _Note that`__(` is not a language construct, it's a WordPress function._ Your problem is that `esc_html` escapes your HTML so that its safe to render as text. Swap it for `wp_kses_post`, and remove the `__` function, you don't want html inside translation strings * * * A sidenote: Frameworks are useful, but they have disadvantages, in order to get help you now need to have the luck of coming across somebody else already familiar with the kirki customizer framework, which I've never heard of. General customizer knowledge is of little to no help, severely limiting your ability to research solutions and get the help of others. In this case, your question was answerable without knowing anything about the customizer
stackexchange-wordpress
{ "answer_score": 0, "question_score": 0, "tags": "theme customizer, links, description" }
dbDelta not CREATING TABLE Here's my code. Please help function lapizzeria_database() { global $wpdb; global $lapizzeria_db_version; $lapizzeria_db_version = "1.0"; $table = $wpdb->prefix . 'reservation'; $charset_collate = $wpdb->get_charset_collate(); //SQL Statement $sql = "CREATE TABLE $table ( id mediumint(9) NOT NULL AUTO_INCREMENT, name varchar(50) NOT NULL, date datetime NOT NULL, email varchar(50) DEFAULT '' NOT NULL, phone varchar(10) NOT NULL message longtext NOT NULL, PRIMARY KEY (id) ) $charset_collate; "; require_once(ABSPATH . 'wp-admin/includes/upgrade.php'); dbDelta($sql); } add_action('after_setup_theme', 'lapizzeria_database');
You are missing comma end of `phone varchar(10) NOT NULL` line, add comma end of line after that table will be created. I have tested < function lapizzeria_database() { global $wpdb; global $lapizzeria_db_version; $lapizzeria_db_version = "1.0"; $table = $wpdb->prefix . 'reservation'; $charset_collate = $wpdb->get_charset_collate(); //SQL Statement $sql = "CREATE TABLE $table ( id mediumint(9) NOT NULL AUTO_INCREMENT, name varchar(50) NOT NULL, date datetime NOT NULL, email varchar(50) DEFAULT '' NOT NULL, phone varchar(10) NOT NULL, message longtext NOT NULL, PRIMARY KEY (id) ) $charset_collate; "; require_once(ABSPATH . 'wp-admin/includes/upgrade.php'); dbDelta($sql); } add_action('after_setup_theme', 'lapizzeria_database');
stackexchange-wordpress
{ "answer_score": 0, "question_score": 0, "tags": "plugins, mysql, dbdelta" }
Add clickable link on an image I'm trying to add an image that when clicked on directs the user to another page on my website. I don't want any visible text link, just the image. How do I do this?
If you're trying to link the image to the page in the post editor you can click on the image and then click the link icon to set the target. You can do the same thing in HTML (in the editor in source view), in a plugin, or in a theme like this: <a href="/link/to/your/page"> <img src="/link/to/your/image" /> </a>
stackexchange-wordpress
{ "answer_score": 2, "question_score": 0, "tags": "images, links" }
Child theme style.css versioning I've been breaking my head on this one. I have a child theme and made changes to the `style.css` document. These changes did not show up in the reload of the page because there is no mention of version in the stylesheet declaration of this file. I have found out that `style.css` is loaded as a foundation of the theme and that the version number in the header of `style.css` is supposed to show up, but it doesn't. I've tried the deregister, dequeue and requeue options that I found online, but still no go. I have made a work around by queueing another css file for which I have added versioning based on the modification date of the file, but I am curious if others have seen this issue and have a proper solution.
Call me silly, but just found a way of getting it enqueued without having it as duplicate. @cjbj, I do really appreciate your help! If you enqueue it in the child theme's `function.php` file (at the end of the stylesheets enqueued in there for priority sake) and make sure you use the exact same handle as the theme is registering it with (look it up in the source code of the page, but without the `-css` at the end), then WP will see it as already registered by the time the theme is trying its standard registration and ignore that. Using `filemtime()` for versioning works perfectly: `wp_enqueue_style( 'theme stylesheet specific handle', get_stylesheet_uri(), array(), filemtime(get_stylesheet_directory() . "/style.css" ) );`
stackexchange-wordpress
{ "answer_score": 1, "question_score": 1, "tags": "theme development, child theme, wp enqueue style, wp register style" }
What is this? MySQL array? In my phpMyAdmin, one meta term, have this value: {a:1:{i:0s:82:" What is this? MySQL array type?
WordPress stores meta and option values in a serialized format if they are objects or arrays. So what you have there is an array (`a`) with an integer (`i`) key `0` and a string (`s`) value with `82` characters.
stackexchange-wordpress
{ "answer_score": 0, "question_score": 0, "tags": "mysql" }
Render ninja form inside markup I want to render a ninja form via markup (in a php file): <div> <h1>hello</h1> <ninja-form> <---- ? </div> What do i put in there to render a particular ninja form?
<?php Ninja_Forms()->display(123) ?>
stackexchange-wordpress
{ "answer_score": 1, "question_score": 1, "tags": "php, templates, plugin ninja forms" }
Problem with add_action I have a function that i need to run every time a subscription status changes to active, This is my code: add_action( 'woocommerce_subscription_status_active', array( __CLASS__,'add_subscription_course_access' ) ); public static function add_subscription_course_access( $order ) { $products = $order->get_items(); $customer_id = $order->get_customer_id(); $courses_id = get_field('user-programs', 'user_'. $customer_id); $courses_id = str_replace("[","",$courses_id); $courses_id = str_replace("]","",$courses_id); $courses_id = explode(",",$courses_id); foreach ( $courses_id as $course_id ) { ld_update_course_access( $customer_id, $course_id ); } } It works on localhost but on a live site its not working!
Yo don't properly call the callback function. If you want to code on oriented object programmation, you have to create your class, and construct function with add_action... Here more informations about it : < or you do something like this (its no POO but its working as well). add_action( 'woocommerce_subscription_status_active', 'add_subscription_course_access' ) ); function add_subscription_course_access( $order ) { $products = $order->get_items(); $customer_id = $order->get_customer_id(); $courses_id = get_field('user-programs', 'user_'. $customer_id); $courses_id = str_replace("[","",$courses_id); $courses_id = str_replace("]","",$courses_id); $courses_id = explode(",",$courses_id); foreach ( $courses_id as $course_id ) { ld_update_course_access( $customer_id, $course_id ); } }
stackexchange-wordpress
{ "answer_score": 1, "question_score": 0, "tags": "plugins, woocommerce offtopic, subscription" }
Custom Post Type - custom form in dashboard I've created my custom post type, let's say called FAQ. I've created it in functions.php. I can also display it in dashboard. The thing is, I don't know how to create form in dashboard, when he clicks on add new FAQ, where admin can fill field (type string) Question, and field Answer. Once I've found some plugin that was capable of creating this kind of forms, but I forgot the name and can't find it :( Thanks!
Ok so I've found what I was looking for. < ACF solved the problem. I can only recommend.
stackexchange-wordpress
{ "answer_score": 1, "question_score": 0, "tags": "plugins, custom post types" }
Script to generate pages - taxonomies not loaded I've created a basic script in my wordpress root folder as a temporary file to generate a batch of new posts. I've included the line: require_once("wp-load.php"); As I've done in the past. I'm encountering problems that certain taxonomies are not seemingly available in this PHP script when calling e.g. $productterms = get_terms( array( 'taxonomy' => 'product-type', 'parent' => 0 ) ); I get a response of invalid-taxonomy. The taxonomy name is definitely correct and this call to retrieve the terms works in functions.php. I suspect I have a load order issue - but can anyone suggest how to work around this? Essentially I just need to have a PHP script that will allow me to loop through an array I've compiled to create pages based on that data - but I need the various taxonomies loaded/available to use.
Probably just use the taxonomy call within wordpress action callback function. add_action('init', 'my_callback_func'); function my_callback_func() { //here you can place your get terms }
stackexchange-wordpress
{ "answer_score": 0, "question_score": 0, "tags": "php, register taxonomy" }
How to override include_once pointed file using add_filter? I want to customize a plugin which uses a file called html-vendor-order-page.php to define the style of contents: include_once( apply_filters( 'wcpv_vendor_order_page_template', dirname( __FILE__ ) . '/views/html-vendor-order-page.php' ) ); I want to create my own html-vendor-order-page.php by modifying this file and force the plugin to use this file instead by using add_filter. I was thinking to filter `__FILE__` which is a defined constant to point to my file. Is that possible?
You can't just filter `__FILE__`. Or any arbitrary function or variable. You can only filter values that are passed to `apply_filters()`. In this case the `wcpv_vendor_order_page_template` filterable value is: dirname( __FILE__ ) . '/views/html-vendor-order-page.php' In other words, it's a path to a PHP file. If you want to change the PHP file that's loaded, you can filter `wcpv_vendor_order_page_template` to pass the path to a file in your theme. So if you create a version of this file in `wp-content/{yourtheme}/wcpv//views/html-vendor-order-page.php`, you can make the plugin load that version like this: add_filter( 'wcpv_vendor_order_page_template', function( $path ) { return get_theme_file_path( 'wcpv//views/html-vendor-order-page.php' ); } );
stackexchange-wordpress
{ "answer_score": 1, "question_score": 0, "tags": "filters, hooks" }
SQL query to change custom field in Wordpress database I'm newbie in SQL questions, and today i have a big problem. I need change many fields in my SQL, about 4,5k. But have some rules to the query change, to don't change wrong fields where don't need changed. In table **wp_postmeta** i have four columns: `meta_id | post_id | meta_key | meta_value` I need change the value of `meta_value`, _BUT ONLY_ if the current value is **'Y'** or **'Empty'** and _REPLACE_ to value **'X'** , AND ONLY in lines where `meta_key` value is **old_price** How i can do it?
Recommend a database backup before you do this. ** updated the statement to specify "Y", empty string, or null ** global $wpdb; $wpdb->query( "update {$wpdb->postmeta} SET meta_value = 'X' WHERE meta_key = 'old_price' AND ( meta_value = 'Y' OR meta_value = '' OR meta_value IS NULL ) );" );
stackexchange-wordpress
{ "answer_score": 0, "question_score": 0, "tags": "mysql, sql, phpmyadmin" }
display post format text in loop If post format is Gallery or another then echo my custom text. Get post format from post id. I want to do like this code in wordpress post loop if (isset(get_post_format(gallery))){ echo 'Gallery'; } Thanks.
`get_post_format()` returns the post format slug for either the current post, when used inside a loop, or a given post, when a `WP_Post` object or an integer post ID is passed to it as a parameter. So, if you're using the function in a posts loop, then you can use it like this, while ( have_posts() ) { the_post(); if ( 'gallery' === get_post_format() ) { echo 'Gallery'; } else { echo 'Not Gallery'; } }
stackexchange-wordpress
{ "answer_score": 1, "question_score": 0, "tags": "loop, gallery, post formats" }
Wordress importing scripts I am fairly new to Wordpress theme development, and I'm trying to structure my code using the best practices possible In your opinion whats the better option to import javascript files: _OPTION 1_ <script src="<?php bloginfo('template_url'); ?>/js/anime.min.js"></script _OPTION 2_ wp_enqueue_script('some_script(s)'); in terms of loading time ? Thanks in advance !
Option 2. Option 1 is just flat out incorrect, not a valid alternative. The proper methods for loading CSS and JavaScript in WordPress are documented here. Also, there's no meaningful performance difference between the two.
stackexchange-wordpress
{ "answer_score": 2, "question_score": 0, "tags": "performance" }
Wrap shortcode inside custom block I use this shortcode very often: `[foo]123[/foo]`. I'd like to drag and drop a custom block in the block editor, instead of typing the shortcode (and making typos). So how do I create a custom block, that just wraps that shortcode?
1. First Add a normal Shortcode block and type the shortcode [foo]123[/foo] 2. Then click More Options for the block and select Add to Reusable Blocks 3. Then provide a name as Foo 4. Next, time you can search and add the Foo block instead of typing the shortcode Thanks
stackexchange-wordpress
{ "answer_score": 1, "question_score": 1, "tags": "shortcode, block editor" }
class 'wphpc_PAnD' not found > **PHP Warning:** `call_user_func_array()` expects parameter 1 to be a valid callback, class `wphpc_PAnD` not found in `/var/www/clients/client32/web3288/web/wp-includes/class-wp-hook.php` on line 288 What can I do?
It is usually caused by a filter or an action not properly declared. Somewhere in your theme or plugins is a line like: add_filter( 'hook_name' , array( 'wphpc_PAnD', 'someMethod' ) ); // or add_action( 'hook_name' , array( 'wphpc_PAnD', 'methodName' ) ); which register class method with hook for a action or filter, but this class ( **`wphpc_PAnD`** ) does not exist. Check if file with class definition is included and there is no typo in the class name in `add_action()` / `add_filter()`.
stackexchange-wordpress
{ "answer_score": 1, "question_score": 0, "tags": "php, warnings" }
how to handle multiple ajax wordpress queries? I am having a problem with two ajax action. I have a post grid it has a frontend sorting "ASC" and "DESC". So if I click on "DESC" it changes the WordPress query arg "order by" to "DESC". It works. But I have load more button which is also ajax. It also works but it does not consider the above case it query args remain the same as initial. So if I click the DESC button and click load more it loads the second page without DESC into consideration. Any possible workaround?
If you have a form you should have a sort field in it, so that you can send your order value on form submit. This way you can send the sorting parameter to your backend callback function. If you don't have a form you shoud add this parameter to another element with a data attribute like that: <button id="load-more" data-order="DESC">Load More</button> And then in your javascript code add this value to the ajax call parameters. Remember that you should change this parameter when you call ajax for sorting.
stackexchange-wordpress
{ "answer_score": 0, "question_score": 1, "tags": "wp query, ajax, pagination" }
How to make 2/3 width column in Gutenberg I created a 2 column layout block, gave the columns block a CSS class of `.first-col-2-3` and added this CSS to my theme: .first-col-2-3 > div:nth-child(1) {background:red;width:67%!important;} .first-col-2-3:nth-child(2) {width:33%!important;} The result is that the columns stay 50% / 50% width. But the first one does get a red background. So the correct column is targeted, yet the width property isn't changing to make the two columms 67% and 33% respectively. How do I make the column widths change? I see a way to add a CSS class to the paragraph within each column but that doesn't work either. Any ideas / solutions? Thank you!
You can add a 2 column block layout where 1 block takes up 2 thirds in the block editor using the UI. Adding CSS classes to achieve this is highly unusual and unnecessary When you add a column block it asks you: ![enter image description here]( Resulting in column blocks spaced for thirds: ![enter image description here]( Each block has a percentage width in the block settings: ![enter image description here]( If you wanted to use the CSS classes from your theme you have several options: * Build a custom columns block * Add CSS classes to the column blocks, completely override or remove the block CSS and add in your own It appears you tried to do the latter, and ran into a 100% pure CSS issue, CSS questions are best asked on stackoverflow (they're offtopic on WPSE as they aren't WordPress questions)
stackexchange-wordpress
{ "answer_score": 1, "question_score": 2, "tags": "block editor, columns" }
jQuery AJAX url wit variable For an AJAX call I try to get the url from a variable jQuery(document).ready(function($) { var url = 'test'; $.ajax({ 'url': url, 'data': ({todo: "food-page_catfetch"}), 'success': function(data) { $('.catspinner__food_page').fadeOut("fast", function(){ $('#food_result__cats').html(data); }); } }); }); If I look in the inspector I see this jQuery(document).ready(function($) { var url = 'test'; $.ajax({ 'url': url, 'data': ({todo: "food-page_catfetch"}), 'success': function(data) { $('.catspinner__food_page').fadeOut("fast", function(){ $('#food_result__cats').html(data); }); } }); }); And I want this 'url': test, I tried different ways but I cant fixed this who can help me?
try with Axios instead jQuery and check the response, example let form_data = new FormData; form_data.append('action', 'myAction'); form_data.append('first_name', 'my first name'); axios.post(myVars.ajax_url, form_data).then(function(response){ console.log('response', response.data); }).cath(console.log)
stackexchange-wordpress
{ "answer_score": 0, "question_score": 0, "tags": "ajax, jquery" }
WordPress Pagination with ajax - Dots I am using `paginate_links()` along with pagination. It works whenever a number is clicked but if I click 3 dots stays there so no 4 pages can't be selected. Is there any workaround? ![enter image description here](
You can use " **mid_size** " to manage number of pages to display in **paginate_links()** function. Please check < for pagination options. Please see example below to use **mid_size**. $args = array( 'mid_size' => 3, 'prev_next' => true, 'prev_text' => '« Previous', 'next_text' => 'Next »', ); $result = paginate_links($args);
stackexchange-wordpress
{ "answer_score": -1, "question_score": 0, "tags": "ajax, pagination, paginate links" }
Return true if parent page id matches I'm trying to write a function (with little luck) that does a simple check against the top level parent page and returns true if the ID matches a supplied ID number. For example; If I'm on page Firefly>Kaylee>Outfits, I will supply my function the ID of the page Firefly (perhaps '29'). The function would return True. If I'm on the page Fringe>Josh>Outfits the same function call would return False because the top level parent (Fringe) does not have the ID of 29. I have seen examples on here that could do this with the direct parent, but they don't work if the page the function is being called from is more than one level deep. How can this be written in a way that it will always find the top most parent no matter how many levels deep the page is that the function is called from, and return True or False? Many thanks, Ben.
You can get all ancestors with `get_post_ancestors`. The root ancestor is the last element of the returned array. Here is the function that checks a target page id against the root ancestor of current page: function check_page_parent( $target_page_id ) { $ancestors = get_post_ancestors( get_the_ID() ); if ( $ancestors ) { $top_most_parent_index = count( $ancestors ) - 1; $top_most_parent_id = $ancestors[ $top_most_parent_index ]; return ( $top_most_parent_id == $target_page_id); } return false; }
stackexchange-wordpress
{ "answer_score": 0, "question_score": 0, "tags": "pages, child pages" }
Is there a loading priority for login_enqueue_scripts? I'm using this function to load my plugins (custom-logo-and-login) Javascript file in the footer of the login.php page, but the file loads right before the wp-includes main jQuery library: add_action( 'login_enqueue_scripts', 'login_js_script' ); function login_js_script() { wp_enqueue_script( 'login-script', plugin_dir_url( __FILE__ ) . 'scripts.js', null, null, true ); } How can I force the priority or loading after the main jQuery file? I can't find a way to add a priority. Do I need to unenqueue the main library and enqueue it later than my file? ![enter image description here](
If you want to load it after jQuery, you can use script dependency... (3rd param) For example if your scripts depends on jQuery, you can use: wp_enqueue_script( 'login-script', plugin_dir_url( __FILE__ ) . 'scripts.js', array( 'jquery' ), null, true );
stackexchange-wordpress
{ "answer_score": 3, "question_score": 0, "tags": "plugins, javascript, wp enqueue script" }
Folder keeps popping up in my public_html directory and overriding Wordpress page structure My client requires that a page have be located at `/connect`, but when accessing the built page, only a parent directory tree is displayed. After a lot of looking around, I found that the problem was caused by the directory `public_html/connect`; a directory completely empty other than a `.well-known` folder. After deleting the folder, the page worked perfectly, but a few days later, the folder came back and broke the page again. Any advice on where could I start looking to find the culprit for this?
I've usually seen a `.well-known` folder associated with site ownership validation for SSL certificates. You may find the following link from Server Fault may assist in further understanding. Maybe you can convince the Client to have a different folder name?
stackexchange-wordpress
{ "answer_score": 1, "question_score": 0, "tags": "directory" }
wp_signon works local, not on https On my localhost environment the following code works perfect $creds['user_login'] = $user_login; $creds['user_password'] = $user_password; $user = wp_signon( $creds, true ); if(!is_wp_error($user)) { wp_redirect('/home'); exit; } But on the server it doesn't work anymore. The user is never logged in. The website is hosted on a https subdomain on an external server. I tried setting a cookie domain in my wp-config: define('COOKIE_DOMAIN', '.domain.com'); And also with the subdomain included: define('COOKIE_DOMAIN', 'sub.domain.com'); Neither worked for me. The server runs on PHP 7.1 with Varnish. Swift Performance is used for caching.
Varnish was the problem. Varnish removes cookies from the response. That's why it didn't work in our case!
stackexchange-wordpress
{ "answer_score": 0, "question_score": 0, "tags": "php, server" }
Custom search with Custom Fields in WP REST API? Good morning! Is there any way to do searches with the WordPress REST API with custom fields, being more specific, I have some custom posts, with a custom field of a specific date, and I want to do a search of those same posts between two specific dates, and that print the result to me in the JSON that WordPress sends
I found this plugin that made my life easier, so I didn't have to code all that <
stackexchange-wordpress
{ "answer_score": 1, "question_score": 2, "tags": "custom post types, custom field, rest api" }
Wordpress page templates in a directory I'm trying to organize my `page-$slug.php` files all inside a folder, i saw in a post that it was possible to store the files inside a directory in the root path of the theme... i tried to store them like this ![enter image description here]( But the `page-termos-e-condicoes.php` wasn't recognized.. is there any other way to do it?
The file needs a template header and will only behave as a user-selectable custom page template. True special templates like `page-$slug.php` that match the post's slug will only work when they live in the root theme directory.
stackexchange-wordpress
{ "answer_score": 3, "question_score": 1, "tags": "theme development, page template, directory" }
Text symbols in the navigation menu Just faced the following issue. The problem is when I paste the font-awesome code in my navigation menu point I see the text `<i class="fa fa-shopping-cart" aria-hidden="true"></i>` (screenshot attached) instead of icon. ![enter image description here]( And I am faced with such a problem for the first time - I never faced this issue on all my previous websites. FontAwesome is successfully integrated - I can see all icons inside my website content. I tried to: * deactivated my custom theme and activated WP default themes * deactivated all my plugins * cleaned cache etc * checked my .htaccess file But unfortunately nothing helped.
WP nav menus don't allow you to paste in HTML directly. **Option 1** Instead, you could create a "Cart" menu item, and use CSS to move the text off the visible page (so screen readers still read it, but sighted visitors don't see it) and add the icon with an :after. (You can add a custom CSS class to the menu item in wp-admin, and use that to identify which link gets the :after and the text moved.) **Option 2** Or, you could use a custom nav walker, which could check if the current menu item links to the cart, and if so, adds the HTML markup you were originally trying to add. **Option 3** You could use `wp_get_nav_menu_items()` (see the Code Reference) to get the items, then use your own custom function to add the HTML markup you were originally trying to add. This might be simpler than the custom walker.
stackexchange-wordpress
{ "answer_score": 1, "question_score": 0, "tags": "navigation, twitter bootstrap" }
Woocommerce pagination problem- page/2 = 404 solution this is not much of a question than a solution to a problem that i couldnt find. Problem: On category archive made with custom query i could not get /page/2 to work ( always 404 ). Tried every possible solution in the book, and finally i reverted back to the original query, there i wanted to change posts per page for this query to check if the problem is caused by my custom query. It appears that woocommerce changes posts per page with Apperance > Customize panel and dosn't use the Settings > Reading page. When you set there the number of items per row * number of rows to match your custom query demand all starts to work fine. Too bad that woocommerce had to make it so weird ( i kinda see the point why it is that way, just its very confusing) :D Anyways i hope this helped someone, i wasted a healthy 2-3 hours on searching for solution. Cheers!
As stated in question, the solution to that problem is to set the woocommerce posts per page ( Apperance > Customize ) and your custom 'posts_per_page' to the same number. Hope it helps.
stackexchange-wordpress
{ "answer_score": 0, "question_score": 0, "tags": "woocommerce offtopic" }
Add a check box in Menu Settings I'm looking for the appropriate hook to add a check box in Menu Settings, and if it exists, how to save the value as an option . ![enter image description here](
Unfortunately there doesn't seem to be any action hooks available for adding custom checkboxes to the Menu Settings section (Github`/wp-admin/nav-menus.php`). For registering menu locations, you should use `register_nav_menus()`.
stackexchange-wordpress
{ "answer_score": 1, "question_score": 0, "tags": "plugin development, hooks" }
How to redirect my custom template page to content-none.php if no posts found? I am trying to redirect from my custom template file to template-parts/content-none.php if my template has no posts in it. I want to add an if condition after while loop checks for posts. Here is my template code <?php $args = array('post_type' => 'post', 'posts_per_page' => -1 ); $the_query = new WP_Query($args); while ($the_query -> have_posts()): $the_query -> the_post(); ?> The posts styling goes here <?php endwhile;?> content i want to show if no posts found
Farhan, this should do it, add an `else` to the `if` statement: $args = [ 'post_type' => 'post', 'posts_per_page' => 1000 ]; $q = new WP_Query($args); if ( $q->have_posts() ) { while ( $q->have_posts() ) { $q->the_post(); ?> <p>The posts styling goes here</p> <?php } // cleanup after the query wp_reset_postdata(); } else { ?> <p>Content I want to show if no posts found.</p> <?php // You could load a sub-template/partial here, e.g.: // get_template_part( 'content', 'none' ); // it won't replace the entire template though }
stackexchange-wordpress
{ "answer_score": 3, "question_score": 0, "tags": "templates" }
Accessing private posts through REST API, same code that works in remote doesn't in local I am capable of fetching private posts through the wp rest api by calling mydomain/wp-json/wp/v2/posts?status=private&slug=whatever I am authenticating well and receiving a valid token, no problems But with the same site running with Laragon (windows 10), while running ok with the authentication, I cannot retrieve the private posts { "code": "rest_invalid_param", "message": "Invalid parameter(s): status", "data": { "status": 400, "params": { "status": "Status is forbidden." } } } I'm getting the same response (as expected) when using Postman and having the `Bearer token` header correctly configured What's going on? I've run out of ideas *I can retrieve public posts
The problem was that I didn't completely clone the wp site, and I forgot to install the plugin that I used to manage user roles The plugin is Members ("User Role Editor by Members – Best User, Role and Capability Management Plugin for WordPress") by MemberPress, and there I can allow the roles that I want to have permissions to read private posts Once that is done, the problem is gone
stackexchange-wordpress
{ "answer_score": 1, "question_score": 0, "tags": "rest api, local installation, private, post status, windows" }
Avoid loading css from parent theme In a parent theme (Foodica Pro) functions.php I have function _foodica_scripts()_ , where css and js are loaded in page header, including: wp_enqueue_style( 'media-queries', get_template_directory_uri() . '/css/media-queries.css', array(), WPZOOM::$themeVersion ); This media-queries.css will take a lot of work to overwrite (using different breakpoints). I want to avoid loading this css file, but without touching parent theme. Is there any way to do it in child theme only?
In your child theme (which I am assuming you are using) `functions.php` file: function wpse_356175_assets() { wp_dequeue_style( 'media-queries' ); } add_action( 'wp_enqueue_scripts', 'wpse_356175_assets' ); Utilise `wp_dequeue_style` and or `wp_deregister_style` depending on how the stylesheet was registered/enqueued. If necessary adjust the priority of your action to fire after the registered/enqueued file from the parent theme, e.g: `add_action( 'wp_enqueue_scripts', 'wpse_356175_assets', 100 );` Useful documentation: * < * <
stackexchange-wordpress
{ "answer_score": 1, "question_score": 1, "tags": "functions, child theme, parent theme" }
how to remove colon and white space in a string by php How can to remove colon's and white space's in a string by php. .e.g: The Godfather: Part II
Check This Code: $demo_string = "The Godfather: Part II"; $demo_string = str_replace(':', '', $demo_string); $demo_string = str_replace(' ', '', $demo_string); output : TheGodfatherPartII
stackexchange-wordpress
{ "answer_score": 4, "question_score": 0, "tags": "php, regex" }
How do i tweak my wp Post title base on category of the post Hello please i need a wordpress function.php code where i can choose how to display my title differently in section wp_title. E.g. If home, tag page, Category page, And Pages are viewed then "Normal Title". But. And then post titles will have a conditional statement like. If a post is under "Music" catgegory then the title will have a prefix "Download Music:" before the post title. E.g Download Music: %post_title% If a post under "Video" category then the title will have another prefix "Download Video:" before the post title. E.g Download Video: %post_title% Etc... I hope i'm understood??.
You can add a filter in the title like: add_filter('the_title', function ($title) { if (is_single()) { $categories = get_the_category(get_the_ID()); // Assuming the post has many categories will take the first $category = reset($categories); return $category->name .' - '.$title; } return $title; });
stackexchange-wordpress
{ "answer_score": 0, "question_score": 0, "tags": "functions, categories, wp title" }
Why does a published post only displays the title and not the content in the site? I published a post last January 3 and it went out fine. Now, I published a post again but the site only displays the title and not the content. This is the first time that this happened to me. Do you have any idea why this happened? I don’t use any plugins and I use a free theme.
### Your content is there BUT hidden from view via CSS styles. _Normally wouldn't provide an answer for this, but it may be helpful to others as it is not uncommong._ This is usually due to CSS styles in external stylesheets, inlined in your `<head>` in of the html document (template header) OR more commonly as inline styles on your content which contain elements such as `<div>`, `<span>` and `<p>` (among) others wrapped around various pieces of your content. In your case it is `<span>` tags See below: ![enter image description here]( ### Solutions If you are using the default WordPress content editor: * switch to the Text tab instead of the Visual tab and remove the span tags OR at least the `display:none` property. If you are using something else like a page builder: * the process should be similar but you may need to consult their documentation By the look if it, you are not though.
stackexchange-wordpress
{ "answer_score": 2, "question_score": 0, "tags": "posts, content, wordpress.com hosting" }
Is it possible to replace PHP with NodeJS? I started working with **WordPress** recently, because I don't have much familiarity with the **PHP** language, I would like to know if there is any way to program with **NodeJS** in WordPress.
No. You can create your custom Node backend that communicates with WordPress via REST or GraphQL, but if you want to use WordPress' functionality (such as `add_filter`, etc.), you need to use PHP. See this as an opportunity to learn a new programming language.
stackexchange-wordpress
{ "answer_score": 6, "question_score": 1, "tags": "customization" }
A post has a js redirection script. How to not redirect its category? I have a post in category A that contain this redirection script: <script>window.location.replace(" However, when I click on A, it also redirects. How to prevent this?
If that redirection script is written in the content section of the post, it is probably being called in with the rest of the content on the category page. You could add a URL check to your javascript that would look like this: if(document.URL.indexOf("foo_page.html") >= 0){ window.location.replace(" } And add in your permalink to the if statement
stackexchange-wordpress
{ "answer_score": 1, "question_score": 1, "tags": "categories, redirect, tags" }
How to ignore folder in site root while accessing a URL I have a folder in my site's public_html directory called `/connect`. The folder is causing the page `sitename.com/connect` to access a parent index page instead of the Wordpress page set up. Deleting this folder solves the problem, but this folder keeps getting added daily by my autoSSL program. It was due to a `connect.sitename.com` subdomain being set up, but even after removing that from the DNS, it is still being added daily. Is there anything that I can do to the htaccess file, or anything else to ignore that folder and use the Wordpress page I've set up? There is no way that I can change the URL, the client has sent out print media with the URL on it.
Ordinarily, requests for physical directories (and files) are not routed to WordPress. You could make an exception for this one folder (or URL) and specifically rewrite requests for `/connect` to `index.php` (the WordPress front-controller). Try the following _before_ the `# BEGIN WordPress` section: # Override directory RewriteRule ^connect index.php [L]
stackexchange-wordpress
{ "answer_score": 1, "question_score": 1, "tags": "htaccess" }
How do I dequeue js/css at the last possible moment? I'm trying to dequeue the font-awesome stylesheet included with the ninja forms plugin (because I manually include the latest FA via a CDN). I did this: add_action('wp_enqueue_scripts', function () { wp_dequeue_style('nf-font-awesome'); }, 100); However the version included in the plugin still loads. So, how do I dequeue a script or stylesheet at the very last moment? I'm obviously not dequeing "late enough", and that's why the above isn't working. What is "later" than `wp_enqueue_scripts`?
I used this to determine which actions were firing, and their order: add_action( 'shutdown', function(){ foreach( $GLOBALS['wp_actions'] as $action => $count ) printf( '%s (%d) <br/>' . PHP_EOL, $action, $count ); }); And that showed me that the ninja forms plugin uses a custom action `nf_display_enqueue_scripts`, which is what I used.
stackexchange-wordpress
{ "answer_score": 0, "question_score": 0, "tags": "actions, wp enqueue script, wp enqueue style" }
customize woocommerce templates and display store on home I'm making some changes to a custom template for a website that wants to add the woocommerce support to create a little shop. I've followed the instruction to add the theme support to the theme, in my function file I have added: add_theme_support('woocommerce'); and the relative hook `after_setup_theme`. I'm not experienced with this plugin, it's the first time I'm using it and I'm still reading the docs. Can anyone explain to me how I can customize the woocommerce templates to use bootstrap 4 and how I can display the products or the store pages on the index of my theme? will the `get_template_part('woocommerce/template-name')` work or there are some particular procedure to follow?
Follow This and Make sure Your Shop or which page you want for default Home page and Then Save Button. ![enter image description here]( ![enter image description here]( Thanks
stackexchange-wordpress
{ "answer_score": 1, "question_score": 0, "tags": "php, woocommerce offtopic" }
alternate left - right content inside the loop I'm not sure if this were asked before. I want to obtain a similar effect where the contents and the images are alternated for each post, one time the image is on the left and the text on the right and for the next row the content is displayed with the image on the right and the text on the left. How I can achieve this inside the loop?
You should be able to get the current index in loop from the global $wp_query object. With the help of modulo you can then set an alternating css class for a post. global $wp_query; while ( have_posts() ) { the_post(); $alignment = ( ($wp_query->current_post + 1) % 2 === 0 ) ? 'even align-right': 'odd align-left'; // post html markup with class="<?php echo $alignment; ?>" }
stackexchange-wordpress
{ "answer_score": 0, "question_score": 0, "tags": "php, theme development" }
Post edit - Media Library - Only get images from current post I've got a few ACF Image fields for `posts` And I want to only query the images in the media library browser already uploaded and used on the current post. In other words, when opening the media library in a image field I only want to see the images of this post. This is what I came up with. But it doesn't work. * I can upload a image to one field * Then in second field I don't see the image from the first field. * (also after saving the post) * It now says `no items found` This is my code: add_filter('ajax_query_attachments_args', 'show_current_post_attachments', 10, 1); function show_current_post_attachments($query = array()) { $post_id = $_POST['post_id'] ; $query['post__in'] = [$post_id]; return $query; }
This will lock uploads to “Uploaded to this post” and will not show “All media items” or other options in WordPress media panels. Add this code to your `function.php` file add_action( 'admin_footer-post-new.php', 'firmasite_mediapanel_lock_uploaded' ); add_action( 'admin_footer-post.php', 'firmasite_mediapanel_lock_uploaded' ); function firmasite_mediapanel_lock_uploaded() { ?> <script type="text/javascript"> jQuery(document).on("DOMNodeInserted", function(){ // Lock uploads to "Uploaded to this post" jQuery('select.attachment-filters [value="uploaded"]').attr( 'selected', true ).parent().trigger('change'); jQuery('#media-attachment-filters').remove(); }); </script> <?php }
stackexchange-wordpress
{ "answer_score": 1, "question_score": 1, "tags": "advanced custom fields, media, attachments, media library, attachment fields to edit" }
My WP-Admin is showing a blank screen When I tried to open the `WP-Admin` of my website, it is showing the blank screen. The `Wp-login.php` is opening but after the login, it is showing the blank screen. So, I first moved my files and DB from the server to my localhost. Then, I renamed the `plugins` folder to `plugins_old`. After then, I replaced the copies of everything except the `wp-config.php` file and the `/wp-content/` directory with fresh copies from the download. This will effectively replace all of your core files without damaging your content and settings. And then when I opened the wp-admin, it showed me to update the database and after updating the database my `wp-admin` opened and I am able to work. In this, by replacing all the files except the `wp-config.php` file and the `/wp-content/` directory, Can I remove the particular set of files to open `wp-admin`? Any help is much appreciated.
First, Renamed the plugins folder to plugins_old. Second, Replaced the copies of everything except the wp-config.php file and the /wp-content/ directory with fresh copies from the download. This will effectively replace all of your core files without damaging your content and settings. I hope this will solve the problem.
stackexchange-wordpress
{ "answer_score": 0, "question_score": 0, "tags": "wp admin" }
What is the best option to convert my WordPress website to French Language? I have my WordPress website in English language and now my client want to convert that website in the French Language also. So, how I can clone my website in French Language. Any help is much appreciated.
I really like the Polylang plugin, but that doesn't handle the translation, only the language switch. The best way to get your site translated is to have a native speaker translate it!
stackexchange-wordpress
{ "answer_score": 1, "question_score": -1, "tags": "multi language, language" }
Omit image captions from get_the_content() I use a theme that calls `get_the_content()` to display short excerpts of the latest blog posts on the home page. Now I noticed that the excerpt sometimes starts with an image caption, if the blog post contains a picture at the very beginning. I usually do that and make the text float around it. I always set the first three caption fields on an image (Alt Text, Title, Caption). Is there any way to strip these image captions from the return value of `get_the_content()` or is there any other method that I could possibly call instead? I checked the documentation, but there seems no argument to exclude images from the return value.
It turned out that the method called `strip_tags(preg_replace(" (\[.*?\])", '', $output))` before `strip_shortcodes($output)`, which caused aforementioned issue, since the code removed shortcode in square brackets, but retained contained image captions. I could fix it by swapping the two method calls like this: $output = get_the_content(); $output = strip_shortcodes($output); // Strip WordPress shortcodes first! $output = strip_tags(preg_replace(" (\[.*?\])", '', $output));
stackexchange-wordpress
{ "answer_score": 3, "question_score": 0, "tags": "images, the content, captions" }
Most efficient way to use classes to create admin pages using Settings API I've built a class which creates admin pages with the Settings API. I'm trying to optimize it to run only where I need it. Most of the examples and tutorials I've seen say to instantiate it from the main plugin file. E.g., `new MyPluginNameClass();` from `my-plugin-name.php.` That's how OptionTree and WPPB do it. But doing it this way creates the class on every page load. The plugin I'm working on is strictly backend. Now, I can wrap my `new MyPluginNameClass()` call in an `is_admin()` conditional to keep it from running on the frontend. But my conditional would still run on every page view, it just exits very quickly on frontend pages. It just feels wrong to run code on every page when I don't need to. Is there an admin-only hook that I should tie my class instantiation to? Or am I just overthinking this by trying to optimize to save nanoseconds?
The example in Settings API documentation uses `admin_init` and `admin_menu` for registering custom settings and admin pages. < There's also an old Codex entry on actions typically run on front and back end requests, which can help pick a suitable action hook. < I also highly recommend the excellent old Q&A about instantiating classes in WP. Best way to initiate a class in a WP plugin?
stackexchange-wordpress
{ "answer_score": 0, "question_score": 1, "tags": "plugins, php, settings api, oop" }
What's the correct way to add capabilites to user roles? A third-party plugin adds the capability 'edit_booked_appointments'. I'd like to assign this capability to the already existing user role 'editor'. I created the following function in my child theme: function add_booking_role_to_editor() { $role = get_role( 'editor' ); $role->add_cap( 'edit_booked_appointments', true ); } add_action( 'init', 'add_booking_role_to_editor'); As far as I understand the whole topic, user roles get written to the database so there is no need to hook this function into the 'init' action. What would be the correct way to do this? Is there a way to fire this once, after the corresponding plugin has been activated? I tried it with the action 'plugins_loaded' but that did not work at all.
The best place to add this would be in the plugin's activation hook. You can either call the dynamic activate_{$plugin} hook, or better yet use the provided register_activation_hook method. Using your code example above - something like this would be what you're looking for: register_activation_hook( __FILE__, function() { $role = get_role( 'editor' ); $role->add_cap( 'edit_booked_appointments', true ); } ); It's also important to clean up after your plugin deactivates by registering a deactivation hook to clean up any DB changes you've made: register_deactivation_hook( __FILE__, function() { $role = get_role( 'editor' ); $role->remove_cap( 'edit_booked_appointments', true ); } ); Note: These code examples are being used in the main plugin file. If you're using it outside of that context, you'll need to provide the main plugin file instead of the magic `__FILE__`.
stackexchange-wordpress
{ "answer_score": 1, "question_score": 0, "tags": "users, actions, user roles, capabilities" }
rearrange the posts by published date in Menu posts selection I need to rearrange the posts by ordering them from published date instead of alphabetical order in Menu posts selection panel, view all section. ![enter image description here]( I want them to order as same way in the most recent posts in the view all section as well. Is it possible to achieve this via a hook or any other code ?
add_action( 'pre_get_posts', 'AS_order_posts_in_menu_admin' ); function AS_order_posts_in_menu_admin( $q ) { global $pagenow; if('nav-menus.php' !=$pagenow) return $q; if(isset($q->query_vars['post_type']) && $q->query_vars['post_type']== 'post'){ $q->query_vars['orderby'] = 'date'; $q->query_vars['order'] = "DESC"; } return $q; }
stackexchange-wordpress
{ "answer_score": 1, "question_score": 0, "tags": "menus, menu order" }
custom post type don’t appear in the home page I would like to have different types of posts on my blog, e.g.: articles, film descriptions, book descriptions, links with short descriptions, quotations, historical events, characters, artwork, musical works, terms, etc. They should be grouped in hierarchical catalogues and hierarchical tags. Theoretically, this plug-in provides me with the possibility to do it: < There is only a problem with it – custom post types don’t appear on the home page: < I’m learning php, but it will take a lot of time before I get the right knowledge. I could hire a programmer, but first I would like to do a good research. I believe that there is another simpler way. Does anyone know it?
Find `functions.php` in your theme and add this code: function add_custom_pt( $query ) { if ( !is_admin() && $query->is_main_query() ) { $query->set( 'post_type', array( 'post', 'cptslug1', 'cptslug2' ) ); } } add_action( 'pre_get_posts', 'add_custom_pt' ); Change array values to match your post type slugs (add as many as you need), but keep 'post'.
stackexchange-wordpress
{ "answer_score": 1, "question_score": 0, "tags": "plugins, custom post types, hierarchical" }
How can I override a require() used in functions.php of parent theme to my child theme I have created a child theme for a Theme, Every thing works fine, except there are some files being required in functions.php of parent theme which I want to override it from the child theme. They have used `get_template_directory_uri();`instead of `get_stylesheet_directory_uri();`. So it's not overriding it. Code used in function.php is: require( get_template_directory() .'/inc/custom-functions.php' ); I can't change the parent theme or unhook from child theme. What is the best solution to use the child one as I can't call both at a time, resulting into fatal error. I have checked some answers on stackoverflow, but they do not answer exactly. Child theme - Overriding 'require_once' in functions.php This answer suggest to use stylesheet instead of template, but I cannot change parent theme.
This is not possible, `require` is a PHP language construct, it's not a WordPress function, and can't be filtered or overriden via WordPress APIs These are your options: If the functionality you want to remove is implemented via actions and filters then: * Unhook the things you don't want from that file * Add new hooks that happen after them that attempt to undo what they did Otherwise, your only options are to: * Modify the parent theme * Fork the parent theme * Choose a new parent theme * Raise a support ticket with the authors to get it changed to support actions and filters
stackexchange-wordpress
{ "answer_score": 3, "question_score": 0, "tags": "theme development, child theme" }
Wordpress Admin Login Issue **Hi Guys, hoping you can help with an issue I am having logging into a WP site. This is the error message I get when trying to log in as Admin:** Warning: Illegal string offset 'remember' in /homepages/13/dxxxxxxxxxx/htdocs/SITENAME/wp-includes/user.php on line 41 Warning: Cannot assign an empty string to a string offset in /homepages/13/dxxxxxxxxxx/htdocs/SITENAME/wp-includes/user.php on line 41 Warning: Illegal string offset 'user_login' in /homepages/13/dxxxxxxxxxx/htdocs/SITENAME/wp-includes/user.php on line 56 Fatal error: Uncaught Error: Cannot create references to/from string offsets in /homepages/13/d516757352/htdocs/SITENAME/wp-includes/user.php:56 Stack trace: #0 /homepages/13/d516757352/htdocs/SITENAME/wp-login.php(806): wp_signon('', '') #1 {main} thrown in /homepages/13/dxxxxxxxxxx/htdocs/SITENAME/wp-includes/user.php on line 56 **Do I need to access this via FTP? Many thanks in advance Kind regards**
Try updating your Wordpress Manually if you are not on the current version: < If you are on the correct version I suggest slowly deleting your most recently installed plugins. If you do not remember, I suggest slowly deleting them one by one and checking to see if you can then login. **NOTE** You do not actually have to delete the plugins, you could rename each one with a singular letter or number to simply remove them from the site but not have to reinstall upon allocating the plugin giving you an issue To find this directory, yes you will need to login to your Cpanel at the following strand: public_html>wp-content>plugins
stackexchange-wordpress
{ "answer_score": 0, "question_score": 0, "tags": "wp admin, login" }
Prevent WordPress from giving each post a number My WordPress blog is giving every entry a number. Even the option to comment under the post and the newsletter opt-in are numbered. It looks like that: 1. Article a 2. Article b 3. Write a comment 4. Subscribe to the newsletter How can I prevent WordPress from doing that?
It is more likely theme is adding numbers rather than Wordpress. Find out the css style associated with the numbering and set its display value to none. If you are using a browser based on Google Chrome you can highlight the article numbers, right click and select _Inspect_. Then, under the Appearance | Customize menu item in your admin dashboard click "Additional CSS". Add the css style you wont to override, for example; if your style is _article_id_number_ do the following. .article_id_number {display:none;} Save the changes and reload your page. The number should be gone. This trick works for anything you don't want displayed, similarly you can override your theme css for any other elements. _Note: If the id number and the article title share the same css style the above wont work for you. In which case contact your theme developer and they might include an option to remove the numbers._ Edit: See my comment below regarding down vote!
stackexchange-wordpress
{ "answer_score": 0, "question_score": 0, "tags": "posts" }
Custom order revolution sliders post base slides as inserted in Specific Posts List field My homepage shows about 10-20 post that are manually selected in a slide. I have used Revolution slider. There is a field `Specific Posts List field` Where I have inserted post Ids `16427,16557,16822,16392,16507` and I want to show them as I have inserted on the field. I found this Helpful in understanding but I don't want to insert a "order" custom field if possible. Another link made me understand what other option I have however don't understand `post__in` and `menu_order`. **Is there a way to show it as my custom list without using custom field?**
function modify_slider_order($query, $slider_id) { if($slider_id == 4) { // $ids=[16427,16557,16822,16507,16392,16548,16564,16426,16412,16404,16419,16421]; $query['orderby'] = 'post__in'; // $query['orderby'] = array ( // 'post__in' => $ids, // 'orderby' => 'post__in', // 'order' => 'ASC' // ); } return $query; } add_filter('revslider_get_posts', 'modify_slider_order', 10, 2); This solved my problem, I'm not sure why I don't even have to pass IDs but this worked.
stackexchange-wordpress
{ "answer_score": 0, "question_score": 0, "tags": "wp query, customization, order" }
What Capability is required to let a role RUN code in Edit Theme? I am outsourcing some work and they are using the Theme Editor to add PHP to my site. For example, this bit of code < is something that I have put into my theme - to invoke it you need to use the querystring < This works fine when logged in as Admin role, however I made a custom Role called "TempCode" that has the Capability EditTheme which lets that user edit the theme fucntions.php file. However, when they try to run it with < when logged in as NON admin it just redirects to the home page. So there's some permissions handler that is check if they have rights to execute that added PHP code - what is the Capability that I need to add to the role to allow them to run it?
WordPress does not have the ability to prevent code from running based on who added it. That's not the problem. The problem is far simpler: the code they added is specifically written to not work for anyone but administrators: if ( empty( $_GET['geolocate_listings'] ) || ! current_user_can( 'administrator' ) ) { return; } You can change `'administrator'` to any capability that you want to control who can trigger this code.
stackexchange-wordpress
{ "answer_score": 1, "question_score": 0, "tags": "user roles, capabilities" }
Where does "rel=0" get removed from my YouTube parameters? I prefer using &rel=0 as a YouTube parameter so that only MY videos get listed in the "More Videos" feature. I have been using the following string in the WordPress editor for a couple of years and it has worked until a day or two ago. Yes, many places inside WordPress "help" in converting that string to what some developer assumes I want, and removes the "rel=0" parameter. Today's result is an iframe like this: <iframe title="Stress Pattern: 2-syllable verbs" width="700" height="394" src=" frameborder="0" allow="accelerometer; autoplay; encrypted-media; gyroscope; picture-in-picture" allowfullscreen></iframe></p> What code stripped the "rel=0" ... and added all those strange "allow" parms?
Iframe content is generated by youtube itself, wordpress just requests it via oembed call. If you wish you can study `wp-includes/class-oembed.php` code, but that will not help you to change iframe parameters. For that you may apply `embed_oembed_html` filter, see < It receives iframe html code, so you can do some string replacements to change it.
stackexchange-wordpress
{ "answer_score": 2, "question_score": 0, "tags": "php" }
Wordpress Playlist WPSE I using the plugin from < so far I really enjoy it, but I hope anyone can help me to change the code little bit, Like: The original code: [_playlist] [_track title="Ain't Misbehavin'" src="//s.w.org/images/core/3.9/AintMisbehavin.mp3"] [_track title="Buddy Bolden's Blues" src="//s.w.org/images/core/3.9/JellyRollMorton-BuddyBoldensBlues.mp3"] [/_playlist] I want to change it to: [_playlist] [/_playlist]
At first glance you just need to change get_tracks_from_content. Rather than running $content through do_shortcodes, * split it by linebreaks (or whitespace?) and discard empty lines, or anything that isn't an URL * probably make the strip_tags call at this point, on each value you have left * pass the URLs into track_shortcode as `[ "src" => $url ]`, plus any other common metadata you want to set here * concatenate the results to make a new $content * continue with the `// Replace last comma` code.
stackexchange-wordpress
{ "answer_score": 1, "question_score": 1, "tags": "playlist" }
Hide "Delete Note" link in Order Notes Panel How do you hide the "Delete Note" link in the Order Notes panel? Is there a hook that can be used? ![Sample order note](
You can try adding this in your functions.php file: add_action('admin_head', 'hide_delete_note_from_edit_order'); function hide_delete_note_from_edit_order() { $screen = get_current_screen(); if ($screen->post_type === "shop_order" && $screen->base === "post") { echo '<style>a.delete_note { display:none; }</style>'; } }
stackexchange-wordpress
{ "answer_score": 0, "question_score": 1, "tags": "woocommerce offtopic" }
301 Redirection After Comment The below code redirects visitors to any page that you want. // Redirect to thank you post after comment add_action('comment_post_redirect', 'redirect_to_thank_page'); function redirect_to_thank_page() { return ' } However, I use WP Multisite feature and the same active theme is used by all subsites in the network. So can I redirect visitors according to the subsite which they visit? i.e. if you leave a comment on example.com/fr, then you'll be redirected automatically to example.com/fr/thank-you page. If we use blog-id or subdirectory name in the above snippet, it might help? **WP Multisite method:** subdirectory Regards.
If you have a thank-you-page with same slug in all sites you can do: add_action('comment_post_redirect', 'redirect_to_thank_page'); function redirect_to_thank_page() { return get_bloginfo('url').'/thank-you-page'; } `get_bloginfo('url')` detects the subsite you're currently in
stackexchange-wordpress
{ "answer_score": 1, "question_score": 0, "tags": "multisite, comments, redirect, wp redirect" }
Echo short code syntax I want to make dynamic short code so insert php code of metabox text value to short code. I wrote this: <?php echo do_shortcode("[svg-flag flag=\"".get_post_meta($post->ID, 'ozellikler_text', true);".\"]"); ?> Error : Parse error: syntax error, unexpected ';', expecting ',' or ')' in /home/deniztas/themeforest-deneme2.deniz-tasarim.site/wp-content/themes/html5blank-stable/my_homepages/right.php on line 14 I explain what I want step by step: There is a short code which shows country flags. [svg-flag flag="tr"] For example, this code shows Turkey (tr) flag. I want to change the `"tr"`to dynamic metabox text value: <?php echo get_post_meta($post->ID, 'ozellikler_text', true) ?> How can I do it? What is true syntax or simpler way than mine? I ask this here instead of stackoverflow because I think maybe it needs wordpress info. **Thanks**
the error is saying to change `;` to `.` \- you will also want to remove the extra `.`: <?php echo do_shortcode("[svg-flag flag=\"" . get_post_meta($post->ID, 'ozellikler_text', true) . "\"]"); ?>
stackexchange-wordpress
{ "answer_score": 0, "question_score": 0, "tags": "php, shortcode" }
get_the_ID() doesnt work Here is my query loop: <?php $query = new \WP_Query( $args ); if ( $query->have_posts() ) { while ( $query->have_posts() ) { $query->the_post(); ?> I want to call $post for this: <div> <?php echo do_shortcode( '[svg-flag flag="' . get_post_meta( $post->ID, 'ozellikler_text', true ) . '"]' ); ?> </div> I tried to call it with this: <?php function get_the_ID() { $post = get_post(); return ! empty( $post ) ? $post->ID : false; } ?> the code doesn't call it. It gives the error: > Fatal error: Cannot redeclare get_the_ID() (previously declared in
get_the_ID is a WordPress core fuction in the global namespace, so you can't make a second function called `get_the_ID` as it won't know which one to use. You should just call get_the_ID() without writing a new function. For your example code, you could do something like this: <div> <?php echo do_shortcode( '[svg-flag flag="' . get_post_meta( get_the_ID(), 'ozellikler_text', true ) . '"]' ); ?> </div>
stackexchange-wordpress
{ "answer_score": 1, "question_score": 0, "tags": "php, wp query" }
Dequeue Table of Content font I have been using Table of Contents plugin on my website. It is slowing my site but I don't want to remove TOC from my site. Is there any way to dequeue TOC fonts.
You can use this code add_action( 'wp_enqueue_scripts', 'dequeue_ez_icomoon', 11 ); function dequeue_ez_icomoon() { wp_deregister_style( 'ez-icomoon' ); wp_deregister_style( 'ez-toc' ); wp_register_style( 'ez-toc', EZ_TOC_URL . "assets/css/screen.min.css", array(), ezTOC::VERSION ); }
stackexchange-wordpress
{ "answer_score": 0, "question_score": 0, "tags": "plugins" }
What is the use case for sharing a term between multiple taxonomies? The `WP_Term::get_instance()` method, used by `get_term()` and presumably other core API functions, accepts an optional `$taxonomy` arg that is "only used for disambiguating potentially shared terms." What is the use case for sharing terms like this? Is it possible to share a term between taxonomies with base WordPress functionality alone, without implementing custom hooks?
The helpful folks on WordPress IRC pointed me to this article, which answered my question: < > In WordPress 4.2, shared taxonomy terms – those items in the wp_terms table that are shared between multiple taxonomies – will be split into separate terms when one of the shared terms is updated. This change (31418) fixes one of WordPress’s most irksome bugs, and is a critical step in our ongoing taxonomy roadmap. Furthermore: > The vast majority of terms are not shared between taxonomies; shared terms themselves are an odd edge case. So basically, this use-case has not been supported for a long time, and was rare to begin with.
stackexchange-wordpress
{ "answer_score": 0, "question_score": 0, "tags": "taxonomy, terms" }
Site downloads files instead of loading them Until two days ago the site was working fine. Yesterday, I've done nothing to it and now when I try to go to the web site it downloads a file that contains: <?php /** * Front to the WordPress application. This file doesn't do anything, but loads * wp-blog-header.php which does and tells WordPress to load the theme. * * @package WordPress */ /** * Tells WordPress to load the WordPress theme and output it. * * @var bool */ define( 'WP_USE_THEMES', true ); /** Loads the WordPress Environment and Template */ require( dirname( __FILE__ ) . '/wp-blog-header.php' ); I've already tried changing the name of the plugin and theme directory to see if the problem comes from there but it didn't helped, I've also tried to rename the .htaccess file but it won't regenerate and I've also verified permissions and they are fine.
Sounds to me like PHP is not running on your system, or (perhaps) an older version of PHP. But you can check PHP status by creating a simple PHP file with the command phpinfo(); in it and loading that page in your browser. That should show you the current settings of PHP, if it is running. And perhaps check with your hosting support to see what they say. There are many googles/bings/ducks about how to ensure PHP is running on your server. I'd start there.
stackexchange-wordpress
{ "answer_score": 1, "question_score": 0, "tags": "php, troubleshooting" }
Redirect based on parameter in url I want to redirect my site to the correct url based on parameter. The url is passed when changing the language of the site using the language switcher. If url contains lang=de, then redirect to example.com/de/ If url contains lang=es, then redirect to example.com/es/ I've tried using the Redirection plugin by John Godley but I'm not sure how to set it up. What's the best way to get this done?
You can use `wp_redirect` with something like... add_action( 'init', 'my_redirect'); function my_redirect() { if (get_query_var('lang') == "de") { wp_redirect( site_url('/de/') ); exit; } }
stackexchange-wordpress
{ "answer_score": 3, "question_score": 1, "tags": "redirect" }
URLs Added to ACF Repeater Field are not working I have created a page using the "Advanced Custom Fields" Plugin and everything is working great except that when I add href url in the field text it doesn't show nicely on Front-end and break the layout: < ![enter image description here]( The field in question is the Repeater field. Does anyone know how to fix it? I appreciate the help!
Its because the wrapper around that text block is set to `display: flex;`. You could override this by adding the following CSS... .special-list .right-text { display: block; } You can add this in Admin > Appearance > Customize > Additional CSS You might want to add this and then test other pages that use this code to make sure it doesn't break anything else.
stackexchange-wordpress
{ "answer_score": 2, "question_score": 0, "tags": "plugins, advanced custom fields, page template" }
I am trying to add current logged in user to my zoho chat I am trying to get user info auto populated into the chat fields so logged in users don't have to type in their information everytime they want to chat with us. I cant seem to figure out how to make the user fetch call to my zoho chat - can any one help? Here's zoho JS API call $zoho.salesiq.ready=function() { $zoho.salesiq.visitor.name("<?php echo $current_user = wp_get_current_user(); ?>"); $zoho.salesiq.visitor.email(); $zoho.salesiq.visitor.contactnumber(); }
As Howdy_McGee said, you need to reference the individual data points, not the whole user object. <?php // Get the user object: username, email, firstname, lastname, displayname, and user ID $current_user = wp_get_current_user(); // Get other user meta, such as phone number // (you'll have to check what meta_key you're using for info like this) $current_user_meta = get_user_meta($current_user->ID); ?> $zoho.salesiq.ready=function() { $zoho.salesiq.visitor.name("<?php echo $current_user->display_name; ?>"); $zoho.salesiq.visitor.email("<?php echo $current_user->user_email; ?>"); $zoho.salesiq.visitor.contactnumber("<?php echo $current_user_meta->phone; ?>"); }
stackexchange-wordpress
{ "answer_score": 2, "question_score": 0, "tags": "javascript, api" }
Interrupting $html.= ' for IF statement Hi Stack Exchange Community, I'm looking to understand how to insert an IF statement inside the code below: $html.= '<span class="cat">In <a href="'. $typeLink . '">' . $terms_string . '</a></span>'; Essentially, I would like to insert a glyph just before the hyperlink that changes based on the value of $terms_string (using IF and ELSEIF). I thought the line below might be close to what I need, but I'm unsure if I'm accurately switching between PHP and HTML (definitely user error, but is it a syntax error?). $html.= '<span class="cat">In '. if($terms_string === "Articles") { glyph HTML code }; .' <a href="'. $typeLink . '">' . $terms_string . '</a></span>'; Any insights would be greatly appreciated.
This is more general PHP than anything WordPress specific. String concatenation occurs whenever you combining two stings with the `.` operator. During string concatenation some basic PHP keywords will not apply and you'll need to use the shorthand equivalent instead. In this case you can use the ternary (conditional) operator $html.= '<span class="cat">In '. ( $terms_string === "Articles" ) ? 'glyph HTML code' : '' .' <a href="'. $typeLink . '">' . $terms_string . '</a></span>'; A better, more readable format may be breaking up the HTML output into multiple strings: $html.= '<span class="cat">In '; if( "Articles" == $terms_string ) { $html .= 'glyph HTML code'; } $html .= '<a href="'. $typeLink . '">' . $terms_string . '</a></span>';
stackexchange-wordpress
{ "answer_score": 2, "question_score": 1, "tags": "php" }
How to include a JSON file on my page? I have a JSON file stored in my child theme directory: file.json). Separately, the PHP template for my page contains some JavaScript code (in the form of a `<script>` tag). In that JS code, I want to write the contents of the JSON file to a variable. What is the proper approach to this? * Can/should I enqueue the JSON file, just as I would a normal JS file (i.e. `wp_enqueue_scripts()`)? If so, how would I in-turn write the contents of the file to a JS variable? Would I do something like `myJson = json.parse(' * Can I just use `include` to include the JSON file on the page? Actually now that I think about it, one can only use `include` with certain file extensions--correct? * Should I perhaps use PHP to save the contents of the JSON file to a PHP variable, then pass that variable to the JS code? Thanks in advance.
You can do this with PHP indeed. The steps are as followed; 1. Get the contents of the JSON file within a variable using `$json = file_get_contents('path-to-file.json')` 2. Inside your `<script>` tags parse the JSON contents within a Javascript variable like this; `var jsonContent = '<?= $json; ?>';` 3. Debug the contents in your Javascript environment using the following; `console.log(JSON.parse(jsonContent));`
stackexchange-wordpress
{ "answer_score": 1, "question_score": 0, "tags": "javascript, json" }
I'd like to be able to programatically setup a site to discourage crawling by search engines I'd like to believe this would be in wp_options, but I can't find the right field.
You're looking for `blog_public`: update_option( 'blog_public', '0' );
stackexchange-wordpress
{ "answer_score": 2, "question_score": 0, "tags": "customization" }
How do we update a custom file upload field with the Advanced Custom Field plugin? ... $filename = mt_rand( 100,999 ) . '.pdf'; $post_id = wp_insert_post( $post_data ); if ( $post_id ) { $pdf_field = get_field_object( $fields['pdf'], $post_id, false, true ); $fields = array( 'pdf' => $pdf_field['key'], ); $pdf_field = array( 'title' => $filename, 'filename' => $filename, 'url' => $uploaded_uri, 'mime_type' => 'application/pdf', 'type' => 'application', 'subtype' => 'pdf', 'icon' => $icon_url, ); update_field( $fields['pdf'], $pdf_field, $post_id ); } ... The function `update_field` returns a custom field's post ID. This means that it is successfully inserting the custom field post. But, when we check the respective post, the file is not attached to it. Any clue what is missing?
File upload fields might _return_ all those values (depending on the field settings), but those are just based on the media library attachment. The field only actually stores the ID of the attachment for the file as its value. So to populate a File field programatically, you just need to set an attachment ID as the field value. So once you have the attachment ID, you just need to do this: update_field( 'field_name', $attachment_id, $post_id );
stackexchange-wordpress
{ "answer_score": 2, "question_score": 0, "tags": "plugins, custom post types, custom field, advanced custom fields" }
Issue with custom loop in Archive page I customized my loop in archive.php to display 8 posts per page. However I have an issue passing the args: the loop displays all my posts from all my categories. Here is my PHP code for the loop: <?php $archive_args = array( 'posts_per_page' => 8 ); query_posts( $archive_args ); if ( have_posts() ) : while (have_posts()) : the_post(); get_template_part( 'template-parts/content', 'archive' ); endwhile; wp_reset_postdata(); else : get_template_part( 'template-parts/content', 'none' ); endif; ?> I tried to use `WP_query();` or `query_posts();` and same issue. Any help would be much appreciated, thanks!
The problem is you aren't saving your custom query's results. To do it your way, you would need to save the query's results to a variable, like so: $myposts = query_posts( $archive_args ); if ( $myposts->have_posts() ) : while ($myposts->have_posts()) : $myposts->the_post(); However, that's not the most efficient way. WP runs the default query in addition to this custom one. So, you would be better off using `pre_get_posts` to alter the main query and just using its results - meaning you would not need to do a custom query or add the `$myposts` part at all. Your `pre_get_posts` filter would just be something simple like: // If this is the main query, not in wp-admin, and it's for an archive if($query->is_main_query() && !is_admin() && $query->is_post_type_archive()) { // Pull 8 posts per page $query->set('posts_per_page', '8'); }
stackexchange-wordpress
{ "answer_score": 1, "question_score": 0, "tags": "php, loop, query, archives" }
Can we use a library under MIT license in a WooCommerce plugin? I am in the process of developing a WooCommerce Plugin, and I plan to make two Free and premium versions. I want to join The `Bootsrap` library which is under the `MIT lisence`. In the WordPress officle directory, I know that `MIT license` is fully GPL compatible. But, my question, can we sell a WooCommerce Plugin that uses 3th part under MIT lisence?
Disclaimer: I'm not a lawyer, so this isn't legal advice. Yes, you can include MIT licensed code in something you sell. The MIT license is very permissive. From the license: > Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the “Software”), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, **and/or sell** copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: > > The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. Also, in contrast to copyleft licenses such as GPLv3, the MIT license _does not_ require that you relicense the rest of your product.
stackexchange-wordpress
{ "answer_score": 1, "question_score": 0, "tags": "plugin development, woocommerce offtopic, licensing" }
Is there a built-in function to generate multiple paragraph tags based on a string with new line separators? Consider the following code <?php // The new line separated string $section_string = <<<EOL Sentence A1. Sentence A2. Sentence A3. Sentence B1. Sentence B2. Sentence B3. Sentence C1. Sentence C2. Sentence C3. EOL; // Is there a function you can call like so: $html_markup = unknown_awesome_function( $section_string ); echo $html_markup; ?> Expected output <p>Sentence A1. Sentence A2. Sentence A3.</p><p>Sentence B1. Sentence B2. Sentence B3.</p><p>Sentence C1. Sentence C2. Sentence C3.</p> Instead of the example fictional `unknown_awesome_function()`, is there a built-in function you can call to generate multiple `<p>` tags based on a string with new line separators?
Have you tried `apply_filters('the_content', $section_string)`? That should apply wp_autop which would add either `<p>` tags or `<br>`s.
stackexchange-wordpress
{ "answer_score": 1, "question_score": 0, "tags": "php, functions" }
WooCommerce which roles and capabilities control user login re-direct to Woo Account Page? WooCommerce has a special "account page" that customers get re-directed to instead of the WordPress admin backend. I'm trying to create a custom role that does NOT go to that page. When I clone "subscriber", it goes to the Woo account page. When I clone "administrator" it goes to the WP backend. Which set or specific capability is handling this? Trying to avoid with custom role: ![enter image description here](
WooCommerce will only show the admin bar and give dashboard access to users who have the `edit_posts` or `manage_woocommerce` capabilities. If you don't want to give users one of those capabilities, you can use the `woocommerce_disable_admin_bar` filter to give access and show the admin bar: add_filter( 'woocommerce_disable_admin_bar', function( $disable_admin_bar ) { if ( current_user_can( 'my_capability' ) ) { $disable_admin_bar = false; } return $disable_admin_bar; } ); Despite the name that will also give access to the dashboard, in addition to showing the admin bar. If you only want to give dashboard access without displaying the admin bar, you can use the `woocommerce_prevent_admin_access` filter, which works exactly the same way, or you can give the user/role the `view_admin_dashboard` capability.
stackexchange-wordpress
{ "answer_score": 1, "question_score": 0, "tags": "woocommerce offtopic, user roles, capabilities" }
which plugin is this? ![which plugin is this]( i want to know which plugin is this or similar types of plugin <
This website is using Woocommerce which is an open-source e-commerce plugin for WordPress. I found it using Builtwith. Cannot say exactly which Product Addon plugin it could be using though. However, If you want a free Wordpress Plugin then you can find it here : * Product Addons for Woocommerce By Acowebs * PPOM for WooCommerce By Najeeb Ahmad I have purely recommended these as a suggestion and do not endorse any of the above plugins. Please vote if I was helpful. Have a nice day.
stackexchange-wordpress
{ "answer_score": 0, "question_score": -3, "tags": "plugins, woocommerce offtopic" }
Get category if used in a custom post type I'm trying to get a list of categories if they are used in a Custom Post type. The post type uses the default categories taxonomy. There are also other custom post types that use the same default WP category. Is it possible to add a meta_query that checks if the category is used in a Custom post_type? eq: custom post type: work. $work_categorys = get_terms( [ 'taxonomy' => "category", 'hide_empty' => true, ] ); foreach ($work_categorys as $key => $value) { echo '<li data-filter-tag="'.$value->slug.'" class="">'.$value->name.'</li>'; }
This would work. As posted by @bucketpress. $someposts = get_posts( array( 'post_type' => 'work', 'posts_per_page' => -1, 'fields' => 'ids', // return an array of ids ) ); $somepoststerms = get_terms( array( 'taxonomy' => 'category', 'object_ids' => $someposts, 'hide_empty' => true, ) );
stackexchange-wordpress
{ "answer_score": 2, "question_score": 0, "tags": "custom post types, categories, terms, meta query, tax query" }
how to remove this image? How to remove this picture. I did not find any option to remove this picture < ![find picture](
You can find these images in the Wordpress widget section. < please check and let me know if this solution worked for you or not.if not then please give me a screenshot of the widget screen I will definitely help you. Thanks.
stackexchange-wordpress
{ "answer_score": 1, "question_score": 0, "tags": "woocommerce offtopic, pages" }
How do i display zip code options during checkout I was recently working on shipping methods in woocommerce that allows customers to pay for a specific shipping fee based on their location. But, during checkout when the country (Nigeria) is selected, post/zip code field disappears. Went ahead to choose a different country and the post/zip code field appears. please, I’ll like to display zip code options during checkout, how do I get this done? I’m so confused. Thank you.
The postcode field was hidden for Nigeria in 3.5, you can see the reasoning given here: < > While the Nigeria Postal Service (< introduced Postal Codes a few years ago, they aren't being used by hardly anyone. > > Nobody knows their postal codes as the implementation is very convoluted and nothing was done to sensitize the public or encourage their use. You won't find them on any addresses and they aren't required for finding a building/location or for delivering parcels. If this is incorrect, you should file an issue. To change this behaviour on one site, though, you can use filter `woocommerce_get_country_locale`, like so: add_filter( 'woocommerce_get_country_locale', function( $locales ) { $locales['NG']['postcode']['hidden'] = false; return $locales; } );
stackexchange-wordpress
{ "answer_score": 0, "question_score": 0, "tags": "woocommerce offtopic" }
Comparing Meta Field date in WPQuery using Meta_Query? I have dates stored in the format d-m-Y, and i want to display any posts that are in the past, before today. $args = array ( 'post_type'=>'property', 'post_status'=>'publish', 'posts_per_page'=> 8, 'paged'=> $paged, 'meta_query' => array( 'key' => 'auction_date', 'value' => date( 'd-m-Y'), 'compare' => '<', 'type' => 'DATE' ), ); This doesn't seem to work and i can't figure out why. Any suggestions would be much appreciated.
ACF stores it's dates in Ymd format, this is why i couldn't compare. Make sure your date is in Ymd format when you compare it against an ACF datefield.
stackexchange-wordpress
{ "answer_score": 0, "question_score": 0, "tags": "wp query, custom field, meta query, date" }
How to only Load scripts on variable products page I'm looking for a way to load my JavaScript and CSS only on the product page, but only if it's a Variable Products. The `is_product()` function works well, but my scripts are loaded for all types of products: Simple, Variable, Grouped ..... How to limit the loading of scripts only for a variable product?
I have already tried this solutions : $the_product = new WC_Product(get_the_ID()); $the_product->get_type(); // Return always "simple" So, I followed the documentation of the code `Class WC_Product()`: /** * Get the product if ID is passed, otherwise the product is new and empty. * This class should NOT be instantiated, but the wc_get_product() function * should be used. It is possible, but the wc_get_product() is preferred. * * @param int|WC_Product|object $product Product to init. */ Now I get the correct product type with this: $the_product = wc_get_product( get_the_ID() ); var_dump( $the_product->get_type() ); The output is correct : string(8) "variable"
stackexchange-wordpress
{ "answer_score": 0, "question_score": -1, "tags": "plugin development, woocommerce offtopic, wp enqueue script, wp enqueue style" }
Gutenberg Gallery Block - How to get the full image url in Javascript/jQuery? I am using jQuery to convert Gutenberg gallery image to clickable lightbox image. In order to do that, I was using jQuery to get the data-full-url attribute but I just found that some images don't have this attribute. I tried to use the srcset attribute but I couldn't find a way to chose the "right" url (the full size one) from the list of urls in jQuery. So, is there a way to get the full image url in jQuery?
You can solve this problem exactly the same way you would if you were using the classic editor. Use the hyperlink `href` attributes. Most lightbox libraries already do this out of the box In order to do this, you'll need to tell the gallery to link to the media files. You can do this in the sidebar like this: ![enter image description here]( You can also register your own gallery block, then deregister the original
stackexchange-wordpress
{ "answer_score": 0, "question_score": 0, "tags": "jquery, block editor" }
Add post-thumbnail after first paragraph including the caption The function below is used to show the post thumbnail after the first paragraph. add_filter( 'the_content', 'insert_featured_image', 20 ); function insert_featured_image( $content ) { global $post; if (has_post_thumbnail($post->ID)) { $caption = '<span class="image-caption">'.get_the_post_thumbnail_caption( $post ).'</span>'; $img = '<p>'.get_the_post_thumbnail( $post->ID, 'full' ).'</p>'; $content = preg_replace('#(<p>.*?</p>)#','$1'.$img . $caption, $content, 1); } return $content; } (Thanks to Add 'if exists' to filter) I have modified it in order to display the caption for the image. However, if there isn't a caption for the featured image, the code still outputs a blank span class="image-caption". Is there a way to include an if-statement? Thanks in advance!
Something like this should work add_filter( 'the_content', 'insert_featured_image', 20 ); function insert_featured_image( $content ) { global $post; if ( has_post_thumbnail($post->ID) ) { $thumbnail_caption = get_the_post_thumbnail_caption( $post ); if ( $thumbnail_caption ) $caption = '<span class="image-caption">' . $thumbnail_caption . '</span>'; else $caption = ''; // You can set this to whatever you want. $img = '<p>' . get_the_post_thumbnail( $post->ID, 'full' ) . '</p>'; $content = preg_replace( '#(<p>.*?</p>)#', '$1' . $img . $caption, $content, 1); } return $content; }
stackexchange-wordpress
{ "answer_score": 1, "question_score": 1, "tags": "post thumbnails, captions" }
Buddypress: adding a new tab direct user to their author page > Hi, This is regarding buddypress adding new tab to the member profile main nav and when is click direct user to the author posts www.mysite.com/Author/username/ After researching and looking I have find this code that it kinder works, it creates a new custom tab and direct users to the new post but the URL is not what i'm looking for it creates member/username/mypost what I need is something like this www.mysite.com/Author/username/ I just don't understand how i can achieve this with this code below.... function ibenic_buddypress_tab() { global $bp; bp_core_new_nav_item( array( 'name' => __( 'My Posts', 'ibenic' ), 'slug' => 'my-posts', 'position' => 100, 'screen_function' => 'ibenic_budypress_my_posts', 'show_for_displayed_user' => true, 'item_css_id' => 'ibenic_budypress_my_posts' ) ); } <
In your screen function `ibenic_budypress_my_posts` create a redirect. Something like: function ibenic_buddypress_tab() { bp_core_new_nav_item( array( 'name' => __( 'My Posts', 'ibenic' ), 'slug' => 'my-posts', 'position' => 100, 'screen_function' => 'ibenic_budypress_my_posts', 'show_for_displayed_user' => true, 'item_css_id' => 'ibenic_budypress_my_posts' ) ); } function ibenic_budypress_my_posts() { $url = '/author/' . bp_get_displayed_user_username(); bp_core_redirect( site_url( $url ) ); }
stackexchange-wordpress
{ "answer_score": 0, "question_score": 0, "tags": "plugin development, buddypress" }
How to set up a If is_singular statement? I've got this code here, and I want it to exclude this div from being parsed if the condition is false. <?php if ( ! is_single() ) { ?> <div class="cat-container"> <a class="post-cat bg-darkpurple" href="<?php echo $category_link ?>"><?php echo $category_name ?></a> </div> <?php } ?> However, It does not work as intended. It's either true or false for all results depending on if ! is included or not. I feel like I'm missing something really simple. Basically, I don't want the div to be sent to the loop If it is a page, not a post(Since pages don't have categories.) I've tried is_single, Is_singluar, and ('post') in there as well, to no avail. Thanks for any insight
`is_single()` and `is_singular()` are not the correct functions to use here. Your comment mentions that this is being added to `search.php`, but `is_single()` and `is_singular()` will always be false on `search.php`, because those functions are checking if the current page is a single post or page, but `search.php` is not. It's is a _list of multiple results_. `is_single()` is not checking the current item in a loop, it's checking, essentially, what is represented by the current _URL_. This is why it's displaying for `! is_single()`, because `is_single()` is `false`, and `! false` is `true`. If you need to determine the post type of a post within a loop, you can use `get_post_type()`: <?php if ( 'post' === get_post_type() ) { ?> <div class="cat-container"> <a class="post-cat bg-darkpurple" href="<?php echo $category_link ?>"><?php echo $category_name ?></a> </div> <?php } ?>
stackexchange-wordpress
{ "answer_score": 2, "question_score": 0, "tags": "php, theme development" }
How to edit checkout page? ![checkout image]( how to edit this text "thank you your order has been received"
Copy the file "/plugins/woocommerce/templates/checkout/thankyou.php" to your theme or child theme ("/yourtheme/woocommerce/checkout/thankyou.php"). And then you will find this code esc_html__( 'Thank you. Your order has been received.', 'woocommerce' ) Change it to whatever you like.
stackexchange-wordpress
{ "answer_score": 0, "question_score": 0, "tags": "plugins, woocommerce offtopic" }
why my price is not showing while adding new product? ![price not showing]( while adding new product why it is not showing the option to enter the price
At the top right, click on `Screen Options` and then select the `Product Data` checkbox. ![enter image description here](
stackexchange-wordpress
{ "answer_score": 0, "question_score": 0, "tags": "woocommerce offtopic" }
How to show Thumbnail size, caption, extension in WordPress? How to show Thumbnail size, caption, extension in WordPress?? ![enter image description here](
Use the Following code, <?php // Get the Featured image ID $thumbnail_id = get_post_thumbnail_id( $post->ID ); $image_data = wp_get_attachment_image_src( $thumbnail_id, 'full' ); $image_url = $image_data[0]; $image_width = $image_data[1]; $image_height = $image_data[2]; // Caption $get_description = get_post( $thumbnail_id )->post_excerpt; // Extinsion $mime_type = get_post_mime_type( $thumbnail_id ); $mime_type = explode( '/', $mime_type ); $extinsion = $mime_type['1']; ?>
stackexchange-wordpress
{ "answer_score": 0, "question_score": 0, "tags": "post thumbnails" }
Copying existing posts after new post type has been added I have some existing posts of some existing type. I have created a new custom post type (with CPT UI). I now want to move these existing posts under the newly-created post type. Is this possible, or do I have to manually copy the content from these posts to have them in the new format? Thank you.
You want move the old posts to new CPT? If you want to move, there is very handy plugin called post type switcher, using it you can easily modify post type of any post and it will automatically be part of new CPT. This is the plugin I mentioned: <
stackexchange-wordpress
{ "answer_score": 1, "question_score": 1, "tags": "custom post types" }
How do I stop plugins and themes from getting updated in a new plugin? I found this 2 filters to add in my `functions.php` of the Theme: add_filter( 'auto_update_plugin', '__return_false' ); add_filter( 'auto_update_theme', '__return_false' ); But I need to do totally block the updates this to multiple WP sites. So I thought to build a plugin that I install where I need instead go every time to change function.php. But is possible to do that with the plugin?
If I understand your question right, you want to disallow updates of themes and updates at all. If I'm right, then this is basically a duplicate of this: <
stackexchange-wordpress
{ "answer_score": 0, "question_score": 0, "tags": "plugins, plugin development, automatic updates" }
There is a page on my website that doesn't show in the Pages section of WordPress I am able to access the page when I type the URL, but the page doesn't exist in the WordPress pages section.
Log in as an admin. Then go to the page. Edit the page (on the black bar at the top of the screen). Then look at all aspects of the page (enable all Screen Options) and see if there is something unusual. The suggestion of temporary disable plugins is a good idea - you can do that quickly with your host's File Manager or FTP by renaming the plugin directory; then look in Admin, Pages; then changing the renamed plugins folder back to normal. You could also try copying all of the page's content (in Text view) to a new page to see if the new page will show up. And look in the error logs to see if there is a hint there.
stackexchange-wordpress
{ "answer_score": 0, "question_score": -2, "tags": "posts" }
Wordpress plugin blog creation I'm trying to create a custom plugin for my website. class SoaneNews { function __construct(){ add_action( 'init', array($this,'pluginprefix_setup_post_type')); } function activate(){ pluginprefix_setup_post_type(); flush_rewrite_rules(); } function deactivate(){ } function pluginprefix_setup_post_type() { register_post_type( 'book', ['public' => 'true',] ); } } if(class_exists('SoaneNews')){ $soanenews = new SoaneNews(); } it will show this fatal error. Fatal error: Uncaught Error: Call to undefined function pluginprefix_setup_post_type() please help me to resolve these issues. Thank You
`pluginprefix_setup_post_type()` is a method inside the `SoaneNews` class, not a function, but inside your `activate()` method you've called a function with that name: function activate(){ pluginprefix_setup_post_type(); flush_rewrite_rules(); } To call the `pluginprefix_setup_post_type()` method from within the class, you need to do it like this: $this->pluginprefix_setup_post_type();
stackexchange-wordpress
{ "answer_score": 0, "question_score": 0, "tags": "plugins, php, plugin development, oop" }
Get site url and updates data, then use them i need to get the url wordpress site and the updates avaible on that site. after get these data use it. to test if i get them I tried to echo in the footer. theoretically I should be able to echo $update // add_action( 'wp_footer', 'my_function' ); function my_function() { $updates = wp_get_update_data(); echo $updates['counts']['title']; echo get_site_url(); echo 'hello world'; } but with it don't echo the number and what need update, but echo only url and hello world
First of all you should perform `$updates = wp_get_update_data();` in the `wp_footer()` body because till then you don't have access to `$updates` variables. add_action( 'wp_footer', 'my_function' ); function my_function() { $updates = wp_get_update_data(); echo $updates['title']; }
stackexchange-wordpress
{ "answer_score": 1, "question_score": 0, "tags": "plugins, updates" }
Get current URL in Form action I am developing a Form in Admin Panel. My Form code is like below <form method="post" action="<?php echo home_url(add_query_arg(array(), $wp->request));?>" name="newAddress" id="createuser" class="validate" novalidate="novalidate"> My Current URL is like below I need below code in Form <form method="post" action="/wordpress123/wp-admin/admin.php?page=newAddress" name="newAddress" id="createuser" class="validate" novalidate="novalidate">
Just use `$_SERVER['REQUEST_URI'];` instead of `home_url(add_query_arg(array(), $wp->request));`
stackexchange-wordpress
{ "answer_score": 1, "question_score": 0, "tags": "wp admin, forms" }
Where does this field get its value? I've inherited maintenance of a wordpress site with a custom template. I'm trying to change the value of a phone number that is displayed throughout the site. I've found the field by looking in the template php files here: <a href="tel:<?php the_field('phone_number', 'option'); ?>"><strong>Phone:</strong> <?php the_field('phone_number', 'option'); ?></a> I tried editing the page to see if there's a box where I can fill this in, but I can't find it anywhere. Is there some sort of global menu for these types of fields?
That clearly is a plugin field of "Advanced Custom Fields". The function: the_field(); is one of the utility functions of the plugin. The purpose of "Advanced Custom Fields" is to enable users with less coding-knowledge to add custom fields to a theme/template. So, in order to reverse engineer the whole thing, you propably need to install and activate "ACF" (very often used as an abbreviation for Advanced Custom Fields). Activate it, and see what happens. In case your installation is missing the necessary data for the plugin, you might have to add them via ACF in the backend. Try to find the field in the backend, which says "phone_number" it should be there, if it is not existent - create it. Here is the plugin's website and here the documentation of the field.
stackexchange-wordpress
{ "answer_score": 2, "question_score": 0, "tags": "custom field, options" }
New Page/Post Screen Opens an Existing Post When I go to add a post or page to my WordPress site, the permalink and featured image are already populated with a 10 year old post, thus we are unable to create new content. **Recent changes done on the site:** * We ran a find-and-replace in wp_posts to rebrand part of our company, however that should only have affected that string inside `<p>` tags since our search included spaces * We deleted old post revisions from the database to make it lighter * We ran a database cleanup plugin I know one solution will be to rollback the database before these changes were made, but this bug was only discovered now (a week later), so recovering from the error is preferable.
Turns out that a previously-modified line in the Yoast SEO source code had been reverted, so this error came back in debug.log: `1Uncaught TypeError: Argument 2 passed to WPSEO_Link_Watcher::save_post() must be an instance of WP_Post, null given`. Disabling Yoast resolved the New Page/Post error, however I believe the root cause was that the database has been around for a few versions of WordPress and needs to be rebuilt soon for better stability (just like re-installing Windows after a couple years). EDIT: So the root cause was that at some point `wp_posts` lost its primary key and had auto-increment disabled on `ID`, so new DB entries were all getting an `ID` of 0. Then, when we tried to restore the backup of that database snapshot, we received import errors because of the duplicate ID entries, causing an incomplete database restore. Once we removed the extra `ID` 0 entries we were able to properly import our database backup and get the site to its former glory.
stackexchange-wordpress
{ "answer_score": 0, "question_score": 0, "tags": "customization, pages, database" }
How do you format the set_body option for WP_Rest_Request? I am looking to pull data from a Google Spreadsheet using SpreadAPI. This is my current code. $request = new WP_REST_Request('POST', ' $request->setBody('{\n"method": "GET",\n"sheet": "date",\n"key": "ACCESS_KEY"\n}'); $response = rest_do_request( $request ); However I'm clearly doing something wrong when it comes to formatting the setBody option. I'm not getting a json response, and I can't seem to find any examples of this in the WordPress documentation. The call works fine when I put it into the RAW section in Postman like this. I'm just not sure how to do that using WordPress. { "method": "GET", "sheet": "date", "key": "ACCESS_KEY" }
`WP_Rest_Request` is not a way to make outgoing calls to remote REST APIs, it's a data object core uses to pass around information about an incoming request. It's basically something you recieved, it isn't something you can send. If you poke your sites REST API with a request, WordPress creates and populates a `WP_Rest_Request` object and uses it to help handle the request. So you cannot use this class to make requests to Google. For that, you want to use the WP_HTTP APIs, such as `wp_remote_get`, or `wp_remote_post`.
stackexchange-wordpress
{ "answer_score": 1, "question_score": 1, "tags": "rest api" }
Pass Variables or Variable Place-Holder from Editor to PHP I'm building a method for my client to construct a message content to be sent with wp_mail. Within that I'd like them to be able to choose variables, for example the message might look like this in my admin custom field: > Email: $email_address$ > > First Name: $first_name$ So that when I iterate over the lines I can spot a variable place-holder and replace $email_address$ with my variable so my PHP would look like: $body = 'Email Address: [email protected]<br>First Name: Mickey Mouse'; wp_mail( $to, $subject, $body, $headers ); I suppose I'm wondering if there's a particular or PHP-ish way to do this, I'm sure I've seen it in plugins before but don't recall the exact formatting.
You should use str_replace, which accepts arrays as arguments: $content = "Email: {{email}}\nFirst Name: {{first_name}}"; $body = str_replace( ['{{email}}', '{{first_name}}'], ['[email protected]', 'Mickey Mouse'], $content ); Be careful about using `$` in your placeholders. Since it's widely used in PHP, it's not safe. It was the reason I've used mustache-like syntax in my example.
stackexchange-wordpress
{ "answer_score": 1, "question_score": 0, "tags": "php, variables, wp mail" }
gutenberg message I created a block template and attached it to my cpt and I get this message on the post page neither of the two buttons or the two links in the vertical dot button work unless I disable `$pages_type_object->template_lock = 'all';` ![enter image description here]( So how can I get rid of this message and keep the `$pages_type_object->template_lock = 'all';`?
seems my problem was in my array 'level' => '3', should've been 'level' => 3,
stackexchange-wordpress
{ "answer_score": 1, "question_score": 0, "tags": "custom post types, block editor" }