INSTRUCTION
stringlengths
11
999
RESPONSE
stringlengths
0
999
SOURCE
stringlengths
16
38
METADATA
dict
Site throws 500 error after upgrading from PHP 5.6 to 7.X If I try to upgrade to PHP 7 or up (from 5.6), I have one site that is throwing a PHP error. I have tried uninstalling all plugins and activating the Twenty Twenty theme before changing PHP version. No dice. Is there a setting in the database or core that would be effecting this? I also tried a default .htaccess file. EDIT: WP debug.log says: [10-Mar-2020 23:35:45 UTC] PHP Fatal error: Allowed memory size of 2097152 bytes exhausted (tried to allocate 32768 bytes) in /path/public_html/wp-includes/formatting.php on line 1600 [10-Mar-2020 23:35:45 UTC] PHP Fatal error: Allowed memory size of 2097152 bytes exhausted (tried to allocate 32768 bytes) in /path/public_html/wp-includes/version.php on line 1 But this seems unrelated, right? The site is having i/o issues as well.
try doing wp_debug true and if the issue is of memory allocation try allocating memory in the wp-config define('WP_MEMORY_LIMIT', '64M'); If it is not fixed try increasing the memory limit.
stackexchange-wordpress
{ "answer_score": 1, "question_score": 0, "tags": "php, debug" }
Plugin throws up 404 on front-end when when enqueuing style with filetime I'm building a very simple plugin to add social media icons to each page on a site that I'm working on. I was expecting the following code to enqueue a stylesheet on the front-end: function myplugin_styles_scripts() { wp_enqueue_style( 'myplugin-style', plugin_dir_path( __FILE__ ) . '/css/style.css', array(), filemtime( plugin_dir_path( __FILE__ ) . '/css/style.css' ) ); } add_action( 'wp_enqueue_scripts', 'myplugin_styles_scripts' ); On the front-end, I get the following error in the console: > < net::ERR_ABORTED 404 The directory and file exist within my plugin. What's causing this?
You're getting the `404` error because you didn't provide the correct URL address of your CSS file. And that's because of the _first_ `plugin_dir_path()` below which outputs a _filesystem_ directory path (e.g. `/home/user/var/www/wordpress/wp-content/plugins/my-plugin/`): wp_enqueue_style( 'myplugin-style', plugin_dir_path( __FILE__ ) . '/css/style.css', array(), filemtime( plugin_dir_path( __FILE__ ) . '/css/style.css' ) ); So you should instead use `plugin_dir_url()` for getting the _URL_ directory path for your plugin (e.g. ` wp_enqueue_style( 'myplugin-style', plugin_dir_url( __FILE__ ) . 'css/style.css', array(), filemtime( plugin_dir_path( __FILE__ ) . '/css/style.css' ) ); And note that both the functions include a trailing slash, so in the above code, I intentionally used `css/style.css` and not `/css/style.css`. Otherwise, the URL would contain `//css/style.css` (note the two slashes).
stackexchange-wordpress
{ "answer_score": 4, "question_score": 0, "tags": "plugins, wp enqueue style" }
Polylang - Remove slug of homepage in secondary language I have a website with polylang and can't seem to figure out how to remove the slug in the homepage of any language that is not the same one. For instance, I have example.com but in english its example.com/en/home. Is there a way to keep it at /en/ ?
Yes it is possible. For a more comprehensive answer, see: <
stackexchange-wordpress
{ "answer_score": 1, "question_score": 4, "tags": "plugin polylang" }
hooks for automatic approve user registration according to data in custom fields good day, my registration form has some custom fields, basically I want to approve the user if and only if some fields are filled with some specific values, if they're not, then these accounts must be manually approved do you know some hook and code that I can use for this purpose?...thank you so much
## Try this if you are using Woocommerce function ws_new_user_approve_registration_message(){ $not_approved_message = '<p class="registration">Send in your registration application today!<br /> NOTE: Your account will be held for moderation and you will be unable to login until it is approved.</p>'; if( isset($_REQUEST['approved']) ){ $approved = $_REQUEST['approved']; if ($approved == 'false') echo '<p class="registration successful">Registration successful! You will be notified upon approval of your account.</p>'; else echo $not_approved_message; } else echo $not_approved_message; } add_action('woocommerce_before_customer_login_form', 'ws_new_user_approve_registration_message', 2);
stackexchange-wordpress
{ "answer_score": 1, "question_score": 0, "tags": "hooks, user registration" }
SQL syntax error. However, it works normally at phpmyadmin I have this error : [You have an error in your SQL syntax; check the manual that corresponds to your MariaDB server version for the right syntax to use near '' at line 4] SELECT COUNT(*) FROM wp_postmeta AS a, wp_postmeta AS b WHERE a.post_id = b.post_id AND (a.meta_key = 'customer_email' AND a.meta_value LIKE '%[email protected]%') AND (b.meta_key = 'usage_count' AND b.meta_value = '0' However, it works normally at PHPMYADMIN I don't know what went wrong. my code is $rowcount = $wpdb->get_var("SELECT COUNT(*) FROM $wpdb->postmeta AS a, $wpdb->postmeta AS b WHERE a.post_id = b.post_id AND (a.meta_key = 'customer_email' AND a.meta_value LIKE '%[email protected]%') AND (b.meta_key = 'usage_count' AND b.meta_value = '0'"); echo $rowcount; How to fix this ?
) bracket missing in last condition. (i.e AND (b.meta_key = 'usage_count' AND b.meta_value = '0'"); ) $rowcount = $wpdb->get_var("SELECT COUNT(*) FROM $wpdb->postmeta AS a, $wpdb->postmeta AS b WHERE a.post_id = b.post_id AND (a.meta_key = 'customer_email' AND a.meta_value LIKE '%[email protected]%') AND (b.meta_key = 'usage_count' AND b.meta_value = '0')"); echo $rowcount;
stackexchange-wordpress
{ "answer_score": 1, "question_score": 0, "tags": "mysql" }
Change menu based on page template via functions.php I'm trying to swap out the main menu of a page if it uses a specific page template. This was working perfectly until I added a 2nd menu to the page. I would greatly appreciate any guidance on how to target only the primary-menu and not all the menus on the page. I tried 'primary-menu' but did not work. In functions.php: add_filter('wp_nav_menu_args', function ($args) { if (is_page_template('page-template-custom.php')) { $args['menu'] = 'custom-menu'; } return $args; }); Thanks very much!
The `$args` the filter is receiving includes the `theme_location` used when the menu was registered, so assuming your main location is `primary`, you can add the following to your if statement to target only that menu: if ( is_page_template( 'page-template-custom.php' ) && isset( $args['theme_location'] ) && 'primary' === $args['theme_location'] ) ) { ... See: < and < for reference
stackexchange-wordpress
{ "answer_score": 1, "question_score": 0, "tags": "functions, menus" }
Finding the path of a specific WordPress install I have recently taken over a WordPress website. Once I got access to the server I found that there were more than 70 installations of WordPress spread across it (files and DBs). What is the quickest/easiest way for me to determine which installation is the one that is running the actual live website? I thought of putting a PHP file into each installation (a file that echoed something along the lines of `$_SERVER['PHP_SELF'];`) - then try and access that file from the site itself, from there I know which installation is the correct one (I can then work out which DB is the correct one from the wp-config). But surely there is an easier way? I have access to wp-admin, is there anything I can do in there to show me the base install path of this particular WordPress?
If you haven't already figured this out, as you have admin access to the dashboard, just go into Appearance->Theme Editor then add some PHP into the theme's footer.php or functions.php to echo out the location of the install on the server.
stackexchange-wordpress
{ "answer_score": 1, "question_score": 1, "tags": "wp filesystem" }
only update titles of single posts The below function wraps all titles of all pages in a * symbol. I want to change the function so that it only applies the filter to titles of single posts. How can I accomplish this? function apply_titles($title, $id) { return "* ".$title." *"; return $title; } add_filter('the_title', 'apply_titles', 10, 2);
If you want to wrap post title of posts only, then you should use `get_post_type()` to check post type of post. You can take reference from below code, it will applied on "post" post type only. and want to apply on post single page then you have to add `is_single()` with `get_post_type()` condition. function apply_titles($title, $id) { if('post' == get_post_type($id) && is_single()) { return "* ".$title." *"; } return $title; } add_filter('the_title', 'apply_titles', 10, 2);
stackexchange-wordpress
{ "answer_score": 0, "question_score": 0, "tags": "functions, filters" }
Use one javascript variable into another javascript file **This is common.js** jQuery(function ($) { var commonJs = { init: function () { }, showAlert: function () { }, } }); **This is add.js** jQuery(function ($) { var addJs = { init: function () { console.log(commonJs.showAlert); }, } }); I want to use common js function **commonJs.showAlert** in add.js How can i access that?
Please simply place commonJs var outside the jQuery function and try again. It will work for you.
stackexchange-wordpress
{ "answer_score": -1, "question_score": 0, "tags": "javascript, jquery, variables" }
Trying to make an image a circle in Gutenberg Gutenberg allows extra CSS styles for an image. I want to make the image a circle and I thought this CSS would work: img.imgcircular { -webkit-clip-path: circle(15.7% at 50% 50%); clip-path: circle(15.7% at 50% 50%); } And the class on the image is "imgcircular" Any ideas why it doesn't work? Thanks
In your `.css` try to add the following : .is-style-circle-mask img, .is-style-rounded img { -webkit-clip-path: circle(15.7% at 50% 50%); clip-path: circle(15.7% at 50% 50%); }
stackexchange-wordpress
{ "answer_score": 0, "question_score": 0, "tags": "css, block editor" }
Is it possible to import several xml from different sites to another? I already have one site running on wordpress, but there are other two I want to combine into this one without losing any content. Is the default import tool helpful in this scenario? I don't want to bring a xml file and find that the content was overriden or something. I need to have the current data, plus 2 sites' data.
Yes, the Core import/export tool will only add content, not overwrite or delete anything old.
stackexchange-wordpress
{ "answer_score": 1, "question_score": 0, "tags": "import" }
How to fix error message to edit sidebar widget text on a livesite childtheme? My WordPress livesite says "An error has occurred. Please reload the page and try again" when I try to edit the sidebar widget text of a twentysixteen child theme. I copied the website to localhost and I did not receive the same error message (I could edit the text just fine). The error occurs with the livesite child theme even with only a "functions.php" file and a "style.css" file. I tried disabling all plugins but I received the same error. The picture below shows me attempting to change the "Directories" name causing error. ![The picture below shows me attempting to change the "Directories" name causing error.](
I fixed the issue. From error_log in public_html/wp-admin I found: ![Error_Log]( I looked some to see whether it was specific to my livesite, something like indexing, but the error was that I closed my functions.php with a "?>" and there may have been whitespace afterwards that was attempted to be sent which caused conflict. I erased the ending "?>" in functions.php for my child theme and I no longer get the error. I'm not currently completely sure why when I duplicated the livesite to localhost of why I did not receive an error in editing the localsite the same way but it's possible that the whitespace was removed.
stackexchange-wordpress
{ "answer_score": 0, "question_score": 0, "tags": "child theme, errors, sidebar, localhost, text" }
Is there any way to get post meta from publish_post hook? I want a post meta of the published post, below is the code but I didn't get it. Appreciate if anyone can help me here: class BarrioBlog { function __construct() { add_action( 'publish_post', array( $this, 'on_publish_post' ), 10, 2 ); } function on_publish_post($post_id, $post) { echo ' custom field: ' . get_field('channel', $post_id); exit; } }
Okay so it was resolved with `do_action( 'acf/save_post', $post_id );`
stackexchange-wordpress
{ "answer_score": 0, "question_score": 0, "tags": "plugin development, hooks" }
How do you enable scripts on a WordPress installation in Softaculous? I am trying to migrate my website from one host to another, and I am not looking for a canned solution. Upon attempting to observe database information in the installation I discovered that the scripts were disabled on the installation that I am trying to migrate. So, I cannot figure out which database is associated with this installation to back it up before the migration. This is a live website, and I am attempting to not break it. How can I re-enable scripts on the installation? What plugins could be responsible for this? I have seen none that are responsible, but I can list those too if necessary. Is there a simple solution? Do I need to update the version, and if so how could I go about discovering the database information first to ensure that I am not going to break the site doing so? ![Software Installations Page in Softaculous](
If you check the `wp-config.php` you can identify which database is being used: // ** MySQL settings - You can get this info from your web host ** // /** The name of the database for WordPress */ define('DB_NAME', 'this_here'); Then, use phpMyAdmin or Adminer to export the data into an .sql and move it over to the new database for import.
stackexchange-wordpress
{ "answer_score": 0, "question_score": 0, "tags": "database, migration, scripts, backup" }
How can I find user role in Mysql? SELECT user_id FROM $wpdb->usermeta WHERE meta_key= .$wpdb->prefix. _capabilities AND meta_value= ROLE in serialized array. How can I set `meta_value` in serialized array? Many thanks in advance :)
I've decided to use plain Key according to @TomJNowell 's comments. If I would like to search a key in serialized data, I would get those serialized array from DB and use maybe_unserialize() in PHP OR use WP_User_Query in PHP. Thank you @TomJNowell
stackexchange-wordpress
{ "answer_score": 0, "question_score": 0, "tags": "database, mysql" }
SKU for each product on every page I got the sku to to show in the cart for each item - Does anyone have the correct php code to get the sku under each product name on all pages?
You can use the `woocommerce_single_product_summary` hook, so code will be like add_action( 'woocommerce_single_product_summary', 'product_sku' ); function product_sku(){ global $product; echo '<div class="sku-product">' . $product->sku . '</div>'; }
stackexchange-wordpress
{ "answer_score": 0, "question_score": 1, "tags": "woocommerce offtopic" }
Global $wp_admin_bar always returns null Developing a plugin and looking to access the $wp_admin_bar global variable and it always returns null? I can output $wp_version fine? function test() { global $wp_admin_bar; var_dump($wp_admin_bar); die; } test(); Anybody know whats going on here?
You need to hook this after admin bar renders for it to work. Also, die() will make WP die. function test() { global $wp_admin_bar; var_dump($wp_admin_bar); } add_action('wp_after_admin_bar_render', 'test');
stackexchange-wordpress
{ "answer_score": 0, "question_score": 0, "tags": "plugins, globals" }
How to add custom script to the particular Product Category page I am trying to add the script to the particular Product Category page, but the code is not adding it to the category. **Page (working):** function wpb_hook_faq_javascript() { if (is_single ('8') || is_page ('8')) { ?> <script type="application/ld+json"> </script> <?php } } add_action('wp_footer', 'wpb_hook_faq_javascript'); **Product Category (not working):** function wpb_hook_faqtocategory_javascript() { if ( in_category( 'category-name' )) { ?> <script type="application/ld+json"> </script> <?php } } add_action('wp_footer', 'wpb_hook_faqtocategory_javascript'); But the above code is not working. **Product Category URL:** wp-admin/term.php?taxonomy=product_cat&tag_ID=9&post_type=product
`in_category()` should be used inside The Loop (unless if you pass a post ID as the second parameter like `in_category( 1, 1 )`) and only for the default/built-in `category` taxonomy. For custom taxonomies like the `product_cat` in your case, you should use `has_term()`; however, if you're checking if the current request/page is a taxonomy archive page, you should instead use `is_tax()`: function wpb_hook_faqtocategory_javascript() { if ( is_tax( 'product_cat', 9 ) ) { // 9 is the term ID, but you can use the slug/name ?> <script type="application/ld+json"> </script> <?php } } Or in WooCommerce (you're using WooCommerce, right?), you can use `is_product_category()`, but you'll need to know the term _slug_ : function wpb_hook_faqtocategory_javascript() { if ( is_product_category( 'term-slug' ) ) { // ... your code here ... } }
stackexchange-wordpress
{ "answer_score": 3, "question_score": 1, "tags": "categories, javascript, actions" }
How do I modify the size of the text in my page titles? Sorry for this basic question, but I'm having a hard time editing the size of text for the titles on the pages on my wordpress website. The html is below <h1 class="hero-title"> COVID Visual </h1> ![banner for Page](
In the CSS you want to set it like this: h1.hero-title, h2.hero-title{ font-size: 24px; } Change the `24px` to whatever size actually works for you.
stackexchange-wordpress
{ "answer_score": 1, "question_score": 0, "tags": "customization, title, headers" }
Specific Page/Post Need to Stay Non SSL I have a website that is already SSL secured. I want to have a plugin that will give me a tick mark option to make the page/post as non-SSL. Rarely I need to use that but that is not a small amount, must be hundreds of pages/posts need to do this. That's why I need a permanent and stable solution for this. Which plugin will give me that option? Thanks
I have found a solution. This plugin gives the option of set SSL on or off based on post or page <
stackexchange-wordpress
{ "answer_score": 0, "question_score": 0, "tags": "security, ssl, https, http" }
Display site language setting in source code I manage a plugin. I have people often complain about translations and have found that sometimes they don't have their site set to their local language. Is it possible in site source code to display the site language as chosen in `Settings > General` ? e.g. I have a comment `<!-- plugin version 123 -->`. Is it possible to display `<!-- plugin version 123 (Fr) -->` if the language is French?
> Is it possible to display `<!-- plugin version 123 (Fr) -->` if the language is French? Yes, it is possible and you can use `get_bloginfo( 'language' )` which returns a language tag like `en-US` for `English (US)`. So if you just want to retrieve the first 2-or-3 character code (e.g. `en` for `en-US` and `en-UK`) of the language tag, you can do: list ( $lang ) = explode( '-', get_bloginfo( 'language' ) ); echo '<!-- plugin version 123 (' . ucfirst( $lang ) . ') -->';
stackexchange-wordpress
{ "answer_score": 1, "question_score": 0, "tags": "plugins, language" }
Website slow : my fault or the host? My website is really slow, and I have no idea why : I read some articles about how to save time and so on but it still takes up to 7s to load a page. Here is the report : < I don't really understand what it says, so I'm open to suggestions to gain some time. If it is due to the host, have you any recommandation in Europe for another host in Europe ? Thank you very much
if ypu fix your host fast problem, I suggest to use a cache plugin like Wp Fastest Cache or Wp Super Cache. Exactly Wp fastest cache plugin is great. We use it on our website, you can take a look from this **link**
stackexchange-wordpress
{ "answer_score": 0, "question_score": 0, "tags": "performance, hosting recommendation" }
Wordpress on localhost working, when sharing IP to connect receive err_connection_refused on .js and .css files **What I have** : as title suggests I set up a WordPress installation on my local machine and can run it and visit it (Mac + MAMP) over `localhost:8888/myBlog`. It works fine. By sharing my IP I am able to reach the WordPress blog from another computer (`myIP:8888/myBlog`). But here is the problem. **The problem** : the page loads, but not the .js, nor the .css. By inspecting the console I see six `ERR_CONNECTION_REFUSED` for js and css files coming from wp-content (.css and .js of a theme I installed) and from wp-includes (again .css and .js files). **What I tried** : I thought it was a problem of permission so I changed the main folder and all the files recursively with chmod -R 575 as suggested somewhere but the problem persists. Thanks!
As discussed in comments, the problem was that the site address was set to `localhost:8888/myBlog`. This is the URL WordPress is expecting your clients to be using, and uses this to generate fully-qualified URLs for scripts and CSS etc. Hence your other clients were trying to load scripts and CSS from their own localhost. The fix is to set the correct URL, ` as the 'WordPress Address' and 'Site Address' under Settings, General.
stackexchange-wordpress
{ "answer_score": 1, "question_score": 1, "tags": "css, javascript, errors, local installation" }
how to get up row in wordpress with wpdb I want to compare two prices in my database. I get a row with any id: $price1 = $wpdb->get_row( "SELECT * FROM $wpdb->prices WHERE id = 10" ); I want to get up the row from this table means I want to get row same bellow but if row by id 9 is deleted it's missing: $price1 = $wpdb->get_row( "SELECT * FROM $wpdb->prices WHERE id = 9" ); How do this?
I found my answer. I have a field that common between these two rows and handle width **limit** parameter in my query. $wpdb->prepare("SELECT * FROM $table_name WHERE post_id = %d ORDER BY id DESC LIMIT 2", $post_id);
stackexchange-wordpress
{ "answer_score": 0, "question_score": 1, "tags": "plugin development" }
plugin_dir_path wrong url echo "background-image: url(" . plugin_dir_path( __FILE__ ) . '/images/bag.png);'; output: url(/home/deniztas/oneclick.deniz-tasarim.site/wp-content/plugins/my_post_plugin-bag2-solda/widgets//images/bag.png) I want this: oneclick.deniz-tasarim.site/wp-content/plugins/my_post_plugin-bag2-solda/widgets//images/bag.png) why /home/.. comes to my url?
because you are using the wrong function. You should use: plugin_dir_url( __FILE__ ) . 'images/bag.png'; Also remove the extra forward slash before images: /images
stackexchange-wordpress
{ "answer_score": 2, "question_score": 0, "tags": "plugin development" }
How do I fire a snackbar notice in admin? I have a custom plugin and want it on occasions to fire the kind of notice that appears and disapears in the left corner like this one: ![snackbar notice]( I found some code in the Gutenberg docs here: const MySnackbarNotice = () => ( <Snackbar> Post published successfully. </Snackbar> ); But adding this to my admin-enqueued js script obviously doesn't work. Thanks!
WordPress has some global actions you can use here. If you want to add your own notice in the lower corner (like the screenshot), you can do that like this: wp.data.dispatch("core/notices").createNotice( "success", // Can be one of: success, info, warning, error. "This is my custom message.", // Text string to display. { type: "snackbar", isDismissible: true, // Whether the user can dismiss the notice. // Any actions the user can perform. actions: [ { url: '#', label: 'View post', }, ], } ); The important part here is `type: "snackbar"`. You can also leave out the snackbar part and it will appear in the UI above the content: ![enter image description here]( Here's the full article on WordPress' Block Editor Handbook: <
stackexchange-wordpress
{ "answer_score": 5, "question_score": 3, "tags": "javascript, block editor, notices" }
What are the "U" and "G" time formats? In WordPress time functions, such as `get_post_time()`, one can pass a couple of formats that I do not understand what they do. Those are `U` and `G`. What are those exactly? Documentation is pretty vague. Thanks.
The `U` and `G` are not WordPress specific. `get_post_time()` is using the same datetime formats as the default PHP `date` method. Here is the documentation for all of the formats: < Specific to the question: `U` is _Seconds since the Unix Epoch (January 1 1970 00:00:00 GMT)_ `G` is _24-hour format of an hour without leading zeros. 0 through 24_
stackexchange-wordpress
{ "answer_score": 2, "question_score": 1, "tags": "date, date time, formatting" }
Add wordpress multi sites with different port number from 80 Firstly I tried to install multi site into sub-directory. At that time, I had problem with port because its not 80. But thanks to this article Cannot install a network of sites - Wordpress and XAMPP , I solved it. So now, I tried to add Wordpress multi site in **My Sites** section of admin screen, but port number is not reflected in URL as below (2nd URL also should be `loclahost:800`) ![enter image description here]( Even if I edit andreplace this URL with `localhost:800`, it was saved as `localhost` automatically. (I think I need to modify some specifi PHP file) Please someone tell me how to add `:800` in 2nd URL too.
You may need to change the values in the wp-options tables. Or (maybe easier), go into the Multisite Admin area, then edit the sites. That gets you into a browser-based editing screens for all of the values in the wp-options table. You can add the port number there. You could also change the port number via the main htaccess file for your site.
stackexchange-wordpress
{ "answer_score": 1, "question_score": 0, "tags": "multisite, urls" }
Gutenberg - reusable blocks that I can edit? Am I being slow? I'm either being incredibly stupid or I've misunderstood a "reusable" Gutenberg block. If I make a block that I need to reuse then it is all very simple to save it and it's placed with the reusable library. However, if I insert it back into the page and try and edit it then edits the entire block. My point is that all I want to do is edit the text - not the layout. What is it that I am doing wrong here?
A reusable block is meant to be a global block...meaning that you can insert it on any page and if the content is updated, it will update across the entire site. This is handy, for instance, for call-to-action content. However, if you want to have a reusable block that has all of the same styling and features, but just need to change the text, you can convert an instance of that block back to a `regular block` by clicking on the three dots (block settings) menu and clicking "Convert to Regular Block": ![enter image description here](
stackexchange-wordpress
{ "answer_score": 0, "question_score": 0, "tags": "block editor" }
What happens to the default query when I use WP_Query? I'm working on a custom theme based on Underscores. In my `archive.php` I want to style the first post in the loop differently than the rest, so I'm running one `WP_Query` to fetch the first post, and another to get the remaining posts. What I'm wondering is -- since I'm handling the queries myself, what happens to the default query that WordPress is running implicitly (that is, the one I'd normally be iterating over with `while ( havePosts() )`? Obviously for performance reasons I don't want to run any unnecessary queries, so is there a way I can stop it? I'm somewhat familiar with the `pre_get_posts` hook, but I'm not sure how I would use it since, as I mentioned, I'm not just trying to modify the one default query -- I need two (unless there's a better way of doing this).
WordPress always queries a default set of posts when you view any sort of archive. So if you run your own query as described you’ll end up with 3 database queries instead of 1. You should not develop your template the way you describe. The standard WordPress templates should all use the default query. You’ll be coming back as the 400th person to ask why pagination isn’t working properly if you do it this way, among other potential issues. If you want to style the first post differently there are plenty of ways to do that without querying it separately, from CSS techniques to logic in the template. If you have something specific you’re trying to accomplish, I suggest posting a new question with those details.
stackexchange-wordpress
{ "answer_score": 2, "question_score": 0, "tags": "wp query, theme development" }
Hide inventory message on product page based on available stock quantity I have a site which needs to display the available stock left for each product, which is fine. However some products are print on demand (i.e. infinite stock) so I have these loaded with 99999999 in stock. Obviously I don't want this stock level to show on the front end of the site as there isn't really any physical stock. I've found the below snippet - can this be edited to say, for example, if the current stock is more than 1000 then hide the stock message? function my_wc_hide_in_stock_message( $html, $text, $product ) { $availability = $product->get_availability(); if ( isset( $availability['class'] ) && 'in-stock' === $availability['class'] ) { return ''; } return $html; } add_filter( 'woocommerce_stock_html', 'my_wc_hide_in_stock_message', 10, 3 );
Yep! You can check using the `get_stock_quantity()` method. function my_wc_hide_in_stock_message( $html, $text, $product ) { $availability = $product->get_availability(); $stock_qty = $product->get_stock_quantity(); if ( isset( $availability['class'] ) && 'in-stock' === $availability['class'] && $stock_qty > 1000 ) { return ''; } return $html; } add_filter( 'woocommerce_stock_html', 'my_wc_hide_in_stock_message', 10, 3 );
stackexchange-wordpress
{ "answer_score": 1, "question_score": 0, "tags": "woocommerce offtopic" }
Need to pull parent category and slug - only pulling daughter category I am tweaking a theme for my friend, and I am using the following: `<?php $category = get_the_category(); ?> <h3 class="omc-blog-two-cat"><a href="<?php echo home_url(); echo ('/category/'.$category[0]->slug); ?>"><?php echo $category[0]->cat_name; ?></a></h3>` This gives website.com/category/categoryslug/, displaying the daughter category slug but I also want the parent category included as well. Ideally as website.com/category/parentcategory/daughtercategory How can I achieve this? Many thanks :D
There are functions for retrieving a term/category link (i.e. URL to the term archive page) and in the case of the default `category` taxonomy, you can use `get_category_link()`: <a href="<?php echo esc_url( get_category_link( $category[0] ) ); ?>"><?php echo $category[0]->name; ?></a> For custom taxonomies, you'd use `get_term_link()`.
stackexchange-wordpress
{ "answer_score": 1, "question_score": 1, "tags": "categories, slug" }
How to make a customize role and view a specific plugins base on that role? is there anyone can suggested or give me an idea. i created a customize WordPress plugin. it was called " **Spark 3cx client** " First when i login using "admin" account. I can view or access the admin dashboard. ![enter image description here]( Then what i wanted is to access the same page of admin to get the same GUI but only the specific plugin will appear on sidebar, using the customize role/user credential when logged in?
You can a custom admin page with `add_menu_page` function. The function has a argument `$capability` which you can set the which users will be able to view and access the page `add_menu_page` < `Roles and capabilities` <
stackexchange-wordpress
{ "answer_score": 1, "question_score": 1, "tags": "plugins, plugin development, menus, user roles, plugin recommendation" }
How to remove google font in WordPress for only single page? I am using WordPress for my site with the Ocean WP Theme and Elementor Page Builder. I can remove Google Fonts from the entire site using below `PHP` snippet: add_filter( 'style_loader_src', function($href){ if(strpos($href, "//fonts.googleapis.com/") === false) { return $href; } return false; }); But I don't want to remove Google Fonts from the entire site. Instead, I want to remove complete Google Fonts from a single page only, so that I can check and compare page speed with and without Google Fonts.
This code filters all style url's. It returns the url if there is no reference to google fonts. It returns 'false' if there is a reference. What you want is to change the condition. It should only return false if there is a reference _and_ you are on a certain page. Logically, this is equivalent to returning the url if there is no reference _or_ you are not on that page. Like this: if ((strpos($href, "//fonts.googleapis.com/") === false) || !is_page(12345)) { Where you should replace 12345 with the ID or slug of the page you want to exclude.
stackexchange-wordpress
{ "answer_score": 1, "question_score": 2, "tags": "filters, css, fonts" }
How can I access variables from theme in child theme? I am using a WordPress theme (Kalium Theme) as a base and extending it with my own child theme, which includes javascript & php files. The parent theme uses a image carousel plugin (Flickity) to display e.g. product image galleries doesn't work exactly the way I want it to. I need access to the flickity instance outside of the Kalium main libraries. Can you advise me on how best to access the carousel objects and manipulate them in javascript without directly changing Kalium Core files? I am talking about adding event listeners to the flickity instance and changing settings in the instance.
You would access it the same way that Kalium does. Code in child and parent themes all have access to the same things, there is no sandboxing or walls of separation dividing the two. Any functions or variables in the parent theme are accessible in the child theme the same way they'd be in the parent. Having said that, overriding PHP functions and classes in the parent theme may not be possible if they don't provide actions and filters, and can't be unhooked. Similarly, javascript is javascript, once it's loaded into the browser page, it has very little to do with WordPress and parent/child themes. You'll probably have to deregister the parent themes javascript and then add your own that does everything the parent theme does, but your way. **Fundamentally, the only people who can definitively answer your question are the Kalium support routes, and other people who use Kalium.**
stackexchange-wordpress
{ "answer_score": 0, "question_score": 0, "tags": "theme development, themes, child theme" }
Woocommerce | Product page seems differently on my 2 websites I want a product page like this: < **( I talk about the "related product" and "add to card" etc. stuffs )** but it seems like this : < how can I fix it? it made by woocommerce
> On plugin page on wp-admin,there is a warning/notification that says continue woocommerce installation/costimization.I clicked it, then a few settings dissapeared on my screen.I clicked next and next buttons then When I checked my product page, the settings came automatically.
stackexchange-wordpress
{ "answer_score": 0, "question_score": -2, "tags": "woocommerce offtopic" }
Single posts for one CPT UI post type are 404s I have an instance of WordPress with multiple custom post types created with the CPT UI plugin. The posts for one of the custom post types are shown on the front end as 404s. The other custom post types are fine. I've tried flushing permalinks, deleting and remaking the post type, disabling all plugins, changing my theme. I'm not entirely sure what else to check. Thanks in advance for your suggestions, Nathan
Based on our discussion in the comments I think the issue you're experiencing is that you've got a slug conflict with WooCommerce 'downloads'. Your CPT isn't conflicting but the slug it's applying is probably conflicting with WooCommerce's slug for downloads. To rectify this, simply prefix your slug or adjust it: `/dls/` `/nthn_downloads/` `/themename_downloads/` Anything of that sort that'll differentiate it from the download endpoint & urls that WooCommerce generates for downloadable products should be sufficient. Using the CPT UI plugin you would just edit your Post-Type and scroll down to the area pictured here... ![Changing the post-type slug in the CPT UI plugin](
stackexchange-wordpress
{ "answer_score": 0, "question_score": 1, "tags": "custom post types" }
how to add a button next to the wordpress view button? I'm trying to add an example button like in the photo for Wordpress plugin ![example image]( I should create a button that sends me to a page created by me in the wordpress dashboard. It should apply to a post type
i found the solution. the function is `apply_filters( 'page_row_actions', string[] $actions, WP_Post $post )` Code Reference For the custom post type need to not be `hierarchical` and it's work
stackexchange-wordpress
{ "answer_score": 0, "question_score": 1, "tags": "plugins, custom post types, theme development" }
How do I create a filter feature on WordPress? I need to create a filter feature on my site so that when someone enters they may put their car details...make, model, year, mileage...etc. Just like how amazon does it. (see photo). ![enter image description here]( The idea is to have people match the products I sell on my site to their vehicle so that they know what fits their car. Anybody have any suggestions?
I would probably start with this plugin or create a custom post/tax type manually: custom-post-type-ui Use this to create a custom post type and associated taxonomy for the "parts". From there you could build a form with select boxes for each taxonomy (filters) and then a submit button or trigger to get the results. You would end up with a url something like this which would find part for that make,model and year: /?post_type=parts&make=vw&model=golf&year=2018 There is probably a plugin that does it all, but I tend to build from scratch for max flexibility.
stackexchange-wordpress
{ "answer_score": 0, "question_score": 1, "tags": "plugins, filters" }
Moving website from expired domain to an active subdomain I had a website which it’s domain is expired: < I also have another active domain and website: < I have created a subdomain under my active domain: < I copied all content in mrafiee.net foolder (which is an add-on domain in my cpanel) in my host, to old.rafiee.net folder. I expected to reach my website when I go to < but it redirects me to < which is already expired. I would be very grateful if someone can help me to solve this issue. Thansk
This is because the database stores information about the old domain. Open the database in **phpmyadmin** and run this query. The code will replace the old domain with the new one. UPDATE wp_options SET option_value = replace(option_value, ' ' WHERE option_name = 'home' OR option_name = 'siteurl'; UPDATE wp_posts SET guid = replace(guid, ' UPDATE wp_posts SET post_content = replace(post_content, ' ' UPDATE wp_postmeta SET meta_value = replace(meta_value,'
stackexchange-wordpress
{ "answer_score": 0, "question_score": 1, "tags": "subdomains, domain" }
How to get 2 or multiple custom post types in wordpress functions.php I using the below code to get modified data for the post, but I need to get the same modified post for my other custom posts. For example, it works if i change post to test( my custom post type name)"if( 'post' === get_post_type() )", but i need for both test, post and movies etc. function et_last_modified_date_blog( $the_date ) { if ( 'post' === get_post_type() ) { $the_time = get_post_time( 'His' ); $the_modified = get_post_modified_time( 'His' ); $last_modified = sprintf( __( 'Last updated %s', 'Divi' ), esc_html( get_post_modified_time( 'M j, Y' ) ) ); $date = $the_modified !== $the_time ? $last_modified : get_post_time( 'M j, Y' ); return $date; } } add_action( 'get_the_date', 'et_last_modified_date_blog' ); add_action( 'get_the_time', 'et_last_modified_date_blog' );
In your if statement just add more conditions like this. function et_last_modified_date_blog( $the_date ) { if ( 'post' === get_post_type() || 'movies' === get_post_type() || 'etc' === get_post_type()) { $the_time = get_post_time( 'His' ); $the_modified = get_post_modified_time( 'His' ); $last_modified = sprintf( __( 'Last updated %s', 'Divi' ), esc_html( get_post_modified_time( 'M j, Y' ) ) ); $date = $the_modified !== $the_time ? $last_modified : get_post_time( 'M j, Y' ); return $date; } } add_action( 'get_the_date', 'et_last_modified_date_blog' ); add_action( 'get_the_time', 'et_last_modified_date_blog' ); The "||" means OR. So the condition would read If post type equals post or movies or etc.
stackexchange-wordpress
{ "answer_score": 2, "question_score": 1, "tags": "php, posts, customization" }
WooCommerce hide unexisting variations I have 2 products with different properties. 1 product has 5 variations configured and the other 120. However, the maximum possible variations for both products are 144 (not all variations are configured). We notice that the product with 5 variations only shows the 5 variations (so other variations cannot be chosen in the listbox). But for the product with 120 variations it shows the 144 variations. This sometimes leads to the message "Sorry, this product is not available. Pick another combination". Is it possible for product 2 to only have the 120 configured varations show up in the listbox?
We found it ourselves, this is the solution. Add the following snippet in functions.php function wc_increase_variation_threshold( $product ) { return 500; } add_filter( 'woocommerce_ajax_variation_threshold', 'wc_increase_variation_threshold', 10, 2 );
stackexchange-wordpress
{ "answer_score": 0, "question_score": 1, "tags": "woocommerce offtopic" }
Don't show a tag on a post if it is the only post with that tag At the bottom of a post, I show all that tags that post has. If the current post is the only post with tag X, then I don't want tag X to show in the list. Because if someone clicks on that, they'll be taken to an archive page where the post they were just looking at is the only post listed. Useless. Otherwise I don't have a problem with tags that only have one post. It's a custom post type with custom taxonomies (three different taxonomies: topic, name, simile) Here is how I am displaying the topic taxonomy: <p class="meta-tag-list"> <?php echo get_the_term_list( $post->ID, 'topic', '', ' ', '' ); ?> </p> Does a function already exist that would let me do this?
Because get_the_term_list() create the html link for you. So 1. you need to use wp_get_object_terms to get a list of terms info first with count for handling. 2. compare each tag count, if the count > 1 then create the link and output I have just tried. It works <p class="meta-tag-list"> <?php $terms = wp_get_object_terms($post->ID, 'category'); // replace 'category' (default Post post type taxonomy name) with your taxonomy such as 'topic' foreach ($terms as $key => $term) { if( $term->count > 1 ) { // if the count is > 1, output, if not, then nothing will happen $link = get_term_link( $term->term_id ); echo '<a href="' . esc_url( $link ) . '" rel="tag">' . $term->name . '</a>'; } } ?> </p>
stackexchange-wordpress
{ "answer_score": 1, "question_score": 1, "tags": "tags" }
How do I prevent the text overflow in menu? The text in the navigation menu on my site is overflowing the container in the desktop version (no problem on mobile). How do I wrap the text to prevent the overflow? Thanks
If you use your browser's inspector `f12`, you can see your list items have this CSS applied... .sf-menu li { white-space: nowrap; } You need to change it to... .sf-menu li { white-space: normal; } If you already created a child theme you can make the change there. Otherwise, in the admin go to Appearance > Customize > Additional CSS and add the above CSS.
stackexchange-wordpress
{ "answer_score": 2, "question_score": 2, "tags": "menus, css" }
How do I find the directory of a page template? This must be a very amateurish question but... I'm using page templates from the dropdown menu in page editor but I can't find their source code. I know that usually this can be found in themes/"theme name"/page-templates, but no matter how hard I look, I just can't find the files for several of the templates I'm using ("Full-Width Template", "Page with Navigation Only" etc.). Any tips? Thanks a lot!
You can simply right click on your Template Select on the edit page, Inspect Element (on Chrome) then you can check the different options in the select like "page-template.php" as value and find your template file. :) <select id="inspector-select-control-0" class="components-select-control__input"> <option value="">Default</option> <option value="page-my-account.php">My Account</option> </select> It should look like this with your own templates.
stackexchange-wordpress
{ "answer_score": 1, "question_score": 1, "tags": "templates, page template" }
Customize format of settings I am adding some settings to the "General" settings page: add_settings_section( 'foobar_settings_section', 'Foobar Options', [$this, 'foobar_options_callback'], 'general' ); $fields = [ 'foobar_title' => 'Title', 'foobar_link' => 'Link', // lots more ]; foreach ($fields as $fieldKey => $fieldTitle) { add_settings_field( $fieldKey, $fieldTitle, [$this, 'foobar_textbox_callback'], 'general', 'foobar_settings_section', [$fieldKey] ); register_setting('general', $fieldKey, 'esc_attr'); } This just outputs a column of many `input` fields, which functionally is fine. But it makes for confusing UX. Is there a way to generally make this section prettier? E.g. to divide it into subsections, or into columns?
At the moment, this is not possible. Just create your own custom settings page and place your options to it. More details and examples: <
stackexchange-wordpress
{ "answer_score": 0, "question_score": 1, "tags": "settings api" }
Use wp_remote_get to get JSON instagram feed from public profile I'm using the curl php library to get the instagram json feed from a given public profile. I want to use `wp_remote_get()` because on the host I'm using for this project, I don't have the ability to use curl to request the json feed, I've noticed that my actual plugin script will work well on localhost, on netsons and aruba but not on tophost. I don't know if the function included in wordpress will do the same thing so my question is, will `wp_remote_get()` return to me the json feed if I provide the instagram url? See the example above: $feed = wp_remote_get('
Yes, it will do the same thing. Taken from the official docs: /** @var array|WP_Error $response */ $response = wp_remote_get( ' ); if ( is_array( $response ) && ! is_wp_error( $response ) ) { $headers = $response['headers']; // array of http header lines $body = $response['body']; // use the content } < Wether it will work for you though, is a different story. If both curl and javascript are returning `null`, I don't believe the problem is in the tool used to make the request, but rather what/how you're requesting it. If your code works everywhere, but does not work on your current host, then you need to speak with your host. Making the same request in a different way is unlikely to help.
stackexchange-wordpress
{ "answer_score": 0, "question_score": 2, "tags": "php, curl, wp remote get" }
Adding Field in WooCommerce I would like to add a field in WooCommerce checkout page. I would like to use below code. add_filter( 'woocommerce_checkout_fields' , 'my_override_checkout_fields' ); But in which file should I put this code ?
**The short, common answer is:** Inside functions.php file in your theme. **The more advanced answer is:** Well... In any file that is included and executed. One way is to create your own plugin and put that line inside it. Another way is to put it in functions.php file in your theme. Remember, that you should never modify ready themes, so if you use one, you should create a child theme and put that code inside it. And of course it doesn’t need to be exactly functions.php - you can create any file (like inc/woo-functions.php), put that code inside it and then include it in your functions.php file.
stackexchange-wordpress
{ "answer_score": 1, "question_score": 0, "tags": "woocommerce offtopic" }
Wordpress current month users How to display list of current month user in wordpress? <?php $blogusers = get_users( array( 'role' => 'game', 'order' => 'DESC', 'number' => 50) ); foreach ( $blogusers as $user ) { ?> <p class="cardname--text"><?php echo $user->display_name; ?></p> <?php } ?>
You can use the `get_users` function with `date_query` ! $month_users = get_users(array( 'date_query' => array( array( 'after' => 'first day of this month', 'before' => 'last day of this month', 'inclusive' => true ), ), )); if(!empty($month_users)) { foreach($month_users as $k => $v) { echo 'User : '.$v->display_name.'<br>'; } }
stackexchange-wordpress
{ "answer_score": 1, "question_score": 0, "tags": "users" }
How to remove the site health dashboard widget? WordPress 5.4 introduced the _Site Health Status_ dashboard widget (source). The dashboard widget shows the status of the site health check: ![Screenshot of dashboard widgets including the site health status]( How can I remove the _Site Health Status_ dashboard widget?
The following snippet removes the registered site health dashboard widget from the dashboard. Add the code to your plugin or `functions.php` file: add_action('wp_dashboard_setup', 'remove_site_health_dashboard_widget'); function remove_site_health_dashboard_widget() { remove_meta_box('dashboard_site_health', 'dashboard', 'normal'); }
stackexchange-wordpress
{ "answer_score": 6, "question_score": 4, "tags": "wp admin, dashboard, site health widget" }
Default setting permalink /blog/ Does anyone know where to find the setting to disable (or adjust) the /blog/ section in the URL? Other sites I manage don't have this default /blog/ setting. I'm trying to set up the permalinks but it seems that the /blog/ part is fixed and only the path following can be set up. ![screenshot](
You can find the settings in the network admin options. Go to: > WordPress Network Admin › Sites › Edit › Settings › _Permalink Structure_. This is the slug to the settings for the site ID 1: `/wp-admin/network/site-settings.php?id=1`
stackexchange-wordpress
{ "answer_score": 0, "question_score": 1, "tags": "permalinks" }
Embed youtube list with sidemenu opened I'm an editor in a wordpress blog I have embedded an youtube list with this code: [youtube I want that the plalist has the sidemenu opened by defalut. How can I achieve that?
This isn't possible, youtube doesn't provide an embed with an open playlist. If it did, this isn't something that could be resolved from the WordPress end, as it's a Youtube OEmbed issue. You will need to refer to Youtube documentation or their support channels
stackexchange-wordpress
{ "answer_score": 1, "question_score": 1, "tags": "youtube, playlist" }
Cannot use object of type WP_Error function im_add_new_term($name,$tax){ if($tax == "genre"){ return wp_insert_term($name,$tax,array("slug"=>array_search ($name, $genres)))["term_id"]; } else { return wp_insert_term($name,$tax)["term_id"]; } } > Fatal error: Cannot use object of type WP_Error as array in /home/pcodecom/demo.p30code.com/multimedia-2/wp-content/plugins/imdb/imdb.php on line 11
What's `$genres`? I don't see it defined anywhere. And `wp_insert_term()` may return an error, so make sure to check if it is an error. So instead of simply doing `return wp_insert_term($name,$tax)["term_id"]`, you could do something like this: $data = wp_insert_term( $name, $tax ); if ( ! is_wp_error( $data ) ) { return $data['term_id']; }
stackexchange-wordpress
{ "answer_score": 1, "question_score": 2, "tags": "wp error" }
Trying to get property of non-object function im_check_term($name,$tax){ $term = get_term_by("name", $name,$tax); return !is_wp_error($term) ? $term->term_id : false; } Notice: Trying to get property of non-object in /home/pcodecom/demo.p30code.com/multimedia-2/wp-content/plugins/imdb/imdb.php on line 11
If you look at the documentation for `get_term_by()`, you'll see that it: > Will return false if `$taxonomy` does not exist or `$term` was not found. You need to account for this possibility in your code by checking the value of `$term`. You'll also note from the documentation that `get_term_by()` does _not_ return a `WP_Error`, so `is_wp_error()` is not useful. This is what you need: $term = get_term_by( 'name', $name, $tax ); return $term ? $term->term_id : false; The specific error you're seeing is because if `$term` is `false` then `$term->term_id` is invalid code.
stackexchange-wordpress
{ "answer_score": 0, "question_score": 1, "tags": "oop" }
How to add field customizable by the theme editor to your theme? I'm adapting a theme for my use, and it currently doesn't have a field for a banner in the header and I would like to add one. But rather than hardcoding it into the theme, I would like to be able to select the header image with the theme customizer, where can I learn to do that?
**Theme Customization API** on Wordpress Codex: <
stackexchange-wordpress
{ "answer_score": 1, "question_score": 1, "tags": "theme development, theme customizer" }
How do I fetch all comments per post via WP REST API? I am busy trying to understand how WP REST API works in combination with React. When I check the documentation of WP REST API, it confuses me a bit. < For example here, it seems like you have to specifically give the ID of a post in the query to fetch the post. Can we not use a variable for this? If so, how could this be done? And how could we make sure that per post, automatically we also fetch its comments beneath it? I mean, this gets all of the comments: But it does not let me combine this with the posts. How do we relate them with each other? Another example: Would mean that we you fetch the categories of post with ID = 33, but how can we make this generic? Like ` or so?
will return comments for a specific post
stackexchange-wordpress
{ "answer_score": 2, "question_score": 1, "tags": "php, functions, javascript, comments, rest api" }
Adding register & login in Wordpress website I am adding register and login to WordPress website. I am using the following code: <?php $c_user = wp_get_current_user(); if( !is_user_logged_in( $c_user->ID ) ) : echo '<a href="' . esc_url( wp_login_url() ) . '" alt="' . esc_attr_e( 'Login', 'textdomain' ) . '">'; echo _e( 'Login', 'textdomain' ); echo '</a>'; wp_register('', ''); else : echo 'Hello ' . $c_user->display_name; endif; ?> After using the code, only the login text is showing. But I want to add "regsite & login". If the user is login, it should be replaced with display "name & logout" text
integrating some of the suggested functions into your code: <?php $c_user = wp_get_current_user(); if( !is_user_logged_in( $c_user->ID ) ) : echo '<a href="' . esc_url( wp_login_url() ) . '" alt="' . esc_attr( 'Login', 'textdomain' ) . '">'; echo _e( 'Login', 'textdomain' ); echo '</a>'; wp_register(' / ', ''); else : echo 'Hello ' . $c_user->display_name . ', '; echo ' <a href="' . esc_url( wp_logout_url( home_url() ) ) . '" alt="' . esc_attr( 'Logout', 'textdomain' ) . '">'; echo _e( 'Logout', 'textdomain' ); echo '</a>'; endif; ?> some remarks: * for the 'Register' link to show, you need to have ticked in the dashboard: 'Settings' - 'General' - ' **Membership** [ ] Anyone can register * the 'Logout' will redirect to the home page; if you don't want that, remove `home_url()` from the code
stackexchange-wordpress
{ "answer_score": 0, "question_score": 1, "tags": "user registration" }
How to add "Read More..." link in twentytwenty ![enter image description here]( How do i fix this in twentytwenty so i can show a read more button or something ?
By going to the Theme Editor, you can add the following snippet at the end of the _**functions.php**_ file: function twentytwentychild_excerpt_more_add_continue_reading( $more ) { return ' [...] <div class="read-more-button-wrap"><a href="' . get_permalink( get_the_ID() ) . '" class="more-link"><span class="faux-button">Continue reading</span> <span class="screen-reader-text">“' . get_the_title( get_the_ID() ) . '”</span></a></div>'; } add_filter('excerpt_more', 'twentytwentychild_excerpt_more_add_continue_reading' ); Source: <
stackexchange-wordpress
{ "answer_score": 1, "question_score": 1, "tags": "customization, categories, theme development, themes" }
Difference between a default post type and a custom post type? I'm a new user of WP, i have create 6 customs post type where i can change parameters of them in the functions.php of my personnal theme. I can change 'supports' and 'slug'. On my url if i put my cpt label like mysite.fr/editos/ i got the list of my all cpt edito post. I want to use the default post type of WP which is "post", but i want to change the 'supports' and 'slug' and get the same function of listing like above How can I do that ? If it's not possible i will create a new cpt. Regards
Ok thanks to Shaikh Aezaz > Yes you can, check this for reference: developer.wordpress.org/reference/functions/remove_meta_box – Shaikh Aezaz
stackexchange-wordpress
{ "answer_score": 0, "question_score": 0, "tags": "custom post types, slug, post type support" }
How to trace and resolve a theme problem such as flickering links in WordPress? When I hover the mouse/cursor over any link on my website the link flickers and it takes some time for the link to be active. You can see this here ` when you hover over any link on images and text. I have tried to analyze the code of my theme but couldn't find anything obviously connected to the problem. Have you any idea how I could solve this?
If you are still interested to look for the reason, here is the CSS code that cause the flickering (which is a CSS related issue). In the theme's style.css a:focus, a:hover { /* ... */ animation-name: fadeIn; /* <=== this cause the flickering, just comment it out or use another CSS to override this such as animation-name: none; */ /* ... */ } Like @WebElaine mentions, generally if theme has problem, you may consider * contact the author * sometimes, maybe there is chance that you might need to overcome the problem immediately before author updating the theme, you may consider to add your own override. You could do it by using child theme and create your own CSS file.
stackexchange-wordpress
{ "answer_score": 1, "question_score": 0, "tags": "themes, css, html" }
Send admin an email when a user's search has no results I'm new to WordPress. What is the easiest way to trigger an email to admin when a user's search has no results.
You haven't provided much info so I will give you a basic example. You need to find whatever template your theme is using to display the results, possibly search.php. If this isn't your theme create a child theme and duplicate the file that displays the results. This file should already have an `if` statement for displaying the results, possibly an `if/else`. If not you will need to add one. The Else is used for when there are no results. You can grab what was entered in the search with get_search_query(). Inside the else you can use wp_mail() to send an email. For Example: if ( have_posts() ) : while ( have_posts() ) : the_post(); // Code to display your results else: // No results so send an email $query = get_search_query(); $to = '[email protected]'; $subject = 'User Search'; $message = 'User searched ' . $query; wp_mail($to, $subject, $message ); endif;
stackexchange-wordpress
{ "answer_score": 2, "question_score": 0, "tags": "plugins, search, email" }
Show title bar only on archives / hide it on all posts and pages My theme has a title bar below the menu. The title bar displays the Title and a breadcrumbs menu. The code is in a template file called title-bar.php. The title bar now shows up on all pages and on all posts. I want this title bar only to show up on all my custom post type archive pages, but hide it on all other pages and on all single posts including custom post types. How can I do this? IF page type is ARCHIVE: (code for title bar) ELSE: (empty)
You can use `is_post_type_archive()`, which is one of the many conditional tags in WordPress: if ( is_post_type_archive( 'your_post_type' ) ) { // show the title bar } // else, just do nothing
stackexchange-wordpress
{ "answer_score": 1, "question_score": 0, "tags": "customization, archives" }
Connect ACF field + custom taxonomy Given: 1) Advanced Custom Fields. A select field with predefined values. 2) Custom taxonomy of the custom post type. Q: Can I link a selection in the ACF field for automatic taxonomy assignment? For example: if I select "1" in the ACF field, then "1" will be selected automatically in the taxonomy when updating the post.
Simply use the taxonomy field. < You can define which taxonomy to handle and how the appearance should work... ![enter image description here]( Which is awesome, because you optionally can use `radio` or `select` if you don't want the user to set more than one taxonomy term per post. Make sure you always set this to true if you want it work as you have described. ![enter image description here]( You can then define in your custom taxonomy code args `'show_ui' => false`. This will hide the default taxonomy metabox, so you only your acf taxonomy metabox can be used.
stackexchange-wordpress
{ "answer_score": 0, "question_score": 0, "tags": "custom taxonomy, advanced custom fields" }
How to add required fields in user profile admin page? I managed to add custom fields in the user profile admin page like this. The problem is when I add `required="true"` or `required="required"` on fields, the submit button do action without checking required empty inputs. The submit is running by Ajax ? How can I force to make required fields in this admin page ?
Actually, in `profile.php`, `edit-user.php` and `new-user.php`, you have to : 1. add `form-required` class on `<tr>`, not on the input field 2. add `aria-required="true"` on the input field
stackexchange-wordpress
{ "answer_score": 2, "question_score": 0, "tags": "forms, profiles" }
Call to Action Button - Resize Help I need help with resizing the "free quote" action button on my website. It is placed on the menu on the right top corner. I need to resize it to smaller size so that it fits the size with other text on the menu. Link to the site: <
This is not so much a WordPress questions as it is a simple CSS question, but adding this rule to your theme's CSS should make the button text the same size as the surrounding text. .navbar .header-right a { font-size: 11px; } If you also wanted to reduce the overall size of the box that surrounds the text, you could adjust the **padding** (currently set to `padding: 4px 12px 4px;` in the theme's CSS file). .navbar .header-right a { font-size: 11px; padding: 2px 7px; // 2px padding on top and bottom, 7px on right and left } Further Reading: CSS Box Model, Padding.
stackexchange-wordpress
{ "answer_score": 0, "question_score": 0, "tags": "actions, code, buttons" }
How to use apiFetch to get author information in Gutenberg properly? I'm trying to create author info block for posts. So I created a block and tried to use redux to get author info, but could get only author id: const applyWithSelect = withSelect( (select, props) => { return { authorId: select('core/editor').getCurrentPostAttribute('author') } } ); Then I tried to use apiFetch to get author info by its id: const authorApi = apiFetch( { path: `/wp/v2/users/${authorId}` } ).then(data => {console.log(data)}); So it's actually working, I'm getting all author information in my console. But how to get that data values to map through it? What should I insert inside `then()`? I think I should create an empty array and push that data values inside of it. But I don't know how, my knowledge is not enough. Can you help me, please?
Finally, I found out how to do it. Just call fetchApi in componentDidMount and then create a new state in your component and add the response to this state when the request is done: constructor(props) { super(props); this.state = { data: {}, }; } componentDidMount() { apiFetch( { path: '/wp/v2/users/1' } ) .then(data => this.setState({ data })); } then in render: const { data } = this.state; finally in return for example avatar of author: <div className={className}> { data.avatar_url ? (<img src={data.avatar_url['24']} />) : (<></>) } </div>
stackexchange-wordpress
{ "answer_score": 1, "question_score": 0, "tags": "plugin development, rest api, block editor" }
Use $_GET inside a shortcode print empty Array I am using Code Snippets plugins, that allow create shortcodes from the Wordpress Admin panel. I am using a simple shortcode to print some info and works great. Anyway, I want make this add some info if the parameter 'error' is in the url. To make this, I am doing this: add_shortcode( 'my_shortcode', function () { $out = ''; print_r($_GET); //--> prints Array ( ) if(isset($_GET['error'])){ $out .='<div id="login_error">El usuario o contraseña no es correcto.</div>'; } $out .='HTML info'; return $out; } ); Anyway, my URL is < and I think this should be working. Some idea about this problem?
reading about this type of problems (because my template wasn't the problem) and it's a fresh installation. I read that wordpress recommends the use of `$_REQUEST` instead `$_GET` (Anyway I see that other people can use `$_GET` without problems) and tried with `$_REQUEST`, now it's working.
stackexchange-wordpress
{ "answer_score": 1, "question_score": 0, "tags": "plugins, shortcode" }
PHP Notice: Undefined offset: -1 - Navigation Previous/Next I am using this code as part of a navigation plugin i.e. previous, next for custom post types. $pos = array_search( $post_id, $exhibs ); if( $previous ) { $new_pos = $pos - 1; $class = 'nav-previous'; } else { $new_pos = $pos + 1; $class = 'nav-next'; } if( $exhibs[$new_pos] ) { } Which works fine but I am getting a notice PHP Notice: Undefined offset: -1 on this line: if( $exhibs[$new_pos] ) { I think this only happens for the first object in my posts. Any ideas on how to fix this notice?
It depends on number of things * how you want to design, if this is the first post, does it still have previous class? Some design create loops, first post previous will go to the last post like a loop, some design does not display the previous button if it is the first one. * the design will then determine how you will code and create the logic for frontend For instance, I guess your first $pos return 0; $pos = array_search( $post_id, $exhibs ); if( $previous ) { $new_pos = $pos - 1; // if first $pos is 0, the $new_pos is -1 $class = 'nav-previous'; } else { $new_pos = $pos + 1; $class = 'nav-next'; } if( $exhibs[$new_pos] ) { // $exhibs[-1] does not exist, so undefined error occur } Possible correction for avoiding error (it really depends on how you want to design) if( $new_pos > 0 && $exhibs[$new_pos] ) {} // or if( isset( exhibs[$new_pos] ) {}
stackexchange-wordpress
{ "answer_score": 1, "question_score": 0, "tags": "php" }
Any way, hook to add content right before the "read more" link? I'm trying to add the 'Hello world' from this code: add_filter( 'the_content', function( $content ) { return $content . ' <br /> Hello World '; }, 0); Before the "read more" link that that sends to single page. As you can see this code ads the hello word after the "read more", and I would like it just before, but after the rest of the content. Is there a hook for this? If possible I prefer to keep this in functions.php rather than in template.
Yes, you could use the filter `the_content_more_link`. Here is the example add_filter( 'the_content_more_link', 'q363666_tweak_more_link', 10, 2 ); function q363666_tweak_more_link( $more_link, $more_link_text ) { // WordPress prepared the $more_link // you can intercept here and return whatever you need return 'Hello World ' . $more_link; }
stackexchange-wordpress
{ "answer_score": 0, "question_score": 0, "tags": "plugin development, filters, hooks" }
Login redirect. Check user meta and redirect accordingly I have a function that checks some user meta and then redirects based off that. I'm pretty sure this was working before I updated everything on my site. For some reason, now when someone logs in it is always redirecting to `/updated-terms-and-conditions/`. I have checked the user meta after this happens and its set correctly, so I would expect it to redirect to `/`. Any ideas? function redirect_login_to_tos($redirect) { $user_id = get_current_user_id(); $checkout_tos2 = get_user_meta($user_id, 'checkout_tos2', true); $checkout_tos3 = get_user_meta($user_id, 'checkout_tos3', true); if($checkout_tos2 != 'agreed' || $checkout_tos3 != 'agreed'){ $redirect = '/updated-terms-and-conditions/'; }else{ $redirect = '/'; } return $redirect; } add_filter('woocommerce_login_redirect', 'redirect_login_to_tos');
woocommerce_login_redirect is similar to login_redirect and it has a users parameter. That means you don't have to use `get_current_user_id()` (which was returning 0 when I tested it). Instead, replace `get_current_user_id()` with `$user->ID;`. For example: function redirect_login_to_tos($redirect, $user) { $user_id = $user->ID; $checkout_tos2 = get_user_meta($user_id, 'checkout_tos2', true); $checkout_tos3 = get_user_meta($user_id, 'checkout_tos3', true); if($checkout_tos2 != 'agreed' || $checkout_tos3 != 'agreed'){ $redirect = '/updated-terms-and-conditions/'; }else{ $redirect = '/'; } return $redirect; } add_filter('woocommerce_login_redirect', 'redirect_login_to_tos', 10, 2);
stackexchange-wordpress
{ "answer_score": 1, "question_score": 0, "tags": "php, redirect, user meta" }
If I disable screen options, does WP still try to update post meta? I am trying to speed up my WP admin post edit page. (/wp-admin/post.php?post=x&action=edit) This particular site has WooCommerce + other plugins that generate a lot of post meta installed. Most of this post meta does not change. If I uncheck sections in the screen options GUI, does WP still try to update the associated post meta within that section?
> If I uncheck sections in the screen options GUI, does WP still try to update the associated post meta within that section? This won't speed up saving, that markup needs to be generated otherwise JS can't show/hide it on the frontend. On top of that, the data still needs to be saved, but wether that happens is plugin specific. Eitherway this isn't a good route to go down if your saving is slow. Instead of speculating, actually measure what's happening when you save a post using a plugin such as query monitor, or profiling such as XDebug or XHProfile. You might be surprised by what you find ( e.g. making remote requests is super expensive ). Also consider reducing the number of plugins. Note that while you didn't clarify if you were talking about the Block editor, or the classic editor ( or a page builder ), this applies to all of them.
stackexchange-wordpress
{ "answer_score": 0, "question_score": 0, "tags": "post meta, performance, post editor" }
How to get WordPress to send Password Reset Link Email instead of New Password? My WordPress configuration generates a new password and sends it via email whenever a user uses Forgot Password link. How can I make WordPress send a Reset Password link instead of a new password? I want this so that malicious visitors can't use the Forgot Password link on the site and enter someone else's email address to cause an unwanted password reset for that user.
Commentor was correct. A plugin had changed default behavior.
stackexchange-wordpress
{ "answer_score": 0, "question_score": 1, "tags": "security, password" }
How to automatically nofollow a set domains? (I seem to have half of the answer) There we go with my first question ever on WPSE. Hope someone can lend me a hand here :) I am sick of adding nofollow rel attribute manually on every single outbount link. I´m looking for a code snippet to make external links going from my blog posts into a specific set of external domains nofollow. This is tricky because I don´t want all external links to become nofollow. Just the ones under specific domains (there´s like 3 domains I want to nofollow). Any ideas ? P.S.: Someone had already replied to a similar question How to set all external links to a certain domain to "nofollow"? \- I like JMau answer (marked as best answer) except I´m not sure how to insert multiple domain names.
Instead of the linked option you could just go with something using jQuery. Try adding something like this to your primary theme or plugin javascript file. (Usually something like `main.js`.) jQuery( document ).ready( function($) { $( 'a[href^=" a[href^=" ).each( function() { $( this ).attr( 'rel', 'nofollow' ); } ); } ); For any additional URLs you'd simply keep adding `a[href^=" in a comma separated format into the selector.
stackexchange-wordpress
{ "answer_score": 0, "question_score": 1, "tags": "links, nofollow" }
Callback function argument which is required for wp_list_comments () # comments.php <?php $args=array( 'type'=> 'comment', 'callback'=>'my_comment_list', ); ?> <ol class="comments-list"> <?php wp_list_comments($args) ?> </ol> # function.php function my_comment_list($comment,$arg,$depth){ } When trying to create a callback function called my_comment_list, it looks like I need three types of arguments for the callback function, `$ comment, $ arg, $ depth`, My question is: **How do you know you need these arguments for callback function?** and **Where do you get detailed explanations of arguments, etc.?** I usually refer to the below link in Wordpress template tags and functions, but It was not there... Wordpress Developer Resource
`wp_list_comments()` uses `Walker_Comment` class to render the output. See `Walker_Comment->start_el()` method for callback argument: < And `Walker_Comment->end_el()` method for end-callback argument: <
stackexchange-wordpress
{ "answer_score": 2, "question_score": 1, "tags": "comments" }
Trying to hide a button on a specific WordPress Page ID I am trying to hide this button: <button onclick="window.location.href=' Me</button> The entire HTML (for that specific section) is (including the title): <aside id="secondary" class="widget-area"> <div class="about-wrapper"> <h2 class="widget-title">About Me</h2> <p class="about-copy"> text </p> </div> </aside> The Page ID is 52, I checked in the code and saw this: <body class="page-template-default page page-id-52 no-sidebar"> The issue is that there isn't a CSS class....maybe I should add one - or - is there another way to hide this JavaScript button per Page ID in WordPress?
so if you want to remove/hide only the button can do this: 1 - if you have a specific class that hide a element //$class = "youre class"; <button class="<?php if(is_page($page_id)){ echo $class } ?>" onclick="window.location.href=' Me</button> 2 - inline style <button <?php if(is_page($page_id)){ echo "style="display: none"; } ?>" onclick="window.location.href=' Me</button>
stackexchange-wordpress
{ "answer_score": 1, "question_score": 0, "tags": "css" }
grant multiple roles access to specific admin menu item I am writing a plugin that offers an admin menu item which only a specific, custom user role ("customrole" in the example) can access. I have implemented this as follows, and it works: function add_admin_menu() { add_menu_page( 'Custom-Plugin', 'Custom-Plugin', 'customrole', 'custom-plugin', 'init_custom_menu_page' ); } The problem is that the administrator does not have the rights to access this menu item anymore; I would like administrators to still be able to access it, however (and the "customrole"-users). How can I achieve this? I am using the "Members" plugin to create custom user roles if that makes a difference. Thanks in advance!
You shouldn't use Roles to handle permissions for your menu page. Instead, use capabilities, and then assign those capabilities to whichever roles should have access. For example, instead of creating a `customrole` role, use a custom capability like `manage_custom_plugin`: add_menu_page( 'Custom-Plugin', 'Custom-Plugin', 'manage_custom_plugin', 'custom-plugin', 'init_custom_menu_page' ); Now, using the Members plugin you can enter `manage_custom_plugin` into the "Custom Capability" box, and add it to whichever roles you need. In code you would grant this capability to roles using `WP_Roles::add_cap()`, like so: $roles = wp_roles(); $roles->add_cap( 'administrator', 'manage_custom_plugin' ); $roles->add_cap( 'editor', 'manage_custom_plugin' ); Just be aware that these functions write to the database, so should only be run once, on plugin or theme activation.
stackexchange-wordpress
{ "answer_score": 0, "question_score": 0, "tags": "user roles, admin menu, user access, members, plugin members" }
How to select a paragraph other than the 1st to be the post's excerpt? My WordPress website has 3 paragraphs and one featured image in a post. How do I make the last or last before para to be the post description?? Are there any plugins to do that? Am already using All in one Seo pack. But it doesn't have that option.
In WordPress using the Gutenberg Block Editor, in the control panel to the right, you have an excerpt box: ![Gutenberg Block Editor Excerpt]( In the Classic Editor you have a metabox under the main post content area: ![Classic Editor Excerpt]( If you don't see it there, go to the top of your screen, on the right under the WP Admin Bar, click "Screen Options" and make sure the "Excerpt" option is clicked. ![Screen Options](
stackexchange-wordpress
{ "answer_score": 1, "question_score": 0, "tags": "plugins, post meta, excerpt, description" }
How can you get first post, last post and post count in a category? I want to show information about some categories on my site, which would include among other things: * A link to the first post in the category * A link to the last post in the category * The number of posts in the category My plan so far was to use this in a WP_Query $args= array( 'cat'=>$comic, 'orderby'=>'post_date', 'order'=>'DESC', 'post_type'=>'post', 'posts_per_page'=>'-1'); And from there extract the information. But I'm not sure how to get to the first and last result without going through the whole loop, how to get the result count, or if using a WP_Query for this will slow the site down if the category grows too big.
You could use two separate query to get first & last post based on date. $args = array( 'cat' => $comic, 'orderby' => 'post_date', 'post_type' => 'post', 'posts_per_page' => '1' ); $first_post = $last_post = null; // get first post $first_post_query = new WP_Query( $args + array( 'order' => 'DESC' ) ); if ( $first_posts = $first_post_query->get_posts() ) { $first_post = array_shift( $first_posts ); } // last post $last_post_query = new WP_Query( $args + array( 'order' => 'ASC' ) ); if ( $last_posts = $last_post_query->get_posts() ) { $last_post = array_shift( $last_posts ); } // post count: method 1 $post_count = $last_post_query->found_posts; // post count: method 2 $category = get_category( $comic ); $post_count = $category->count;
stackexchange-wordpress
{ "answer_score": 3, "question_score": 1, "tags": "wp query, categories" }
Restore of database doesn't show content I had to reset and reinstall wordpress bescause of compatibility issues between some plug-ins. So as usual, I took a full back-up of the website, databse, home directory, email, etc.... After a new clean wordpress install, I selected my backed-up databse, so wordpress won't create a new one, but even so, all the content and post, pages, images are not showing up in the wordpress dashboard. If I check the database in C Panel with my PHP admin, it shows everything, all the post and pages. But why the hell aren't they showing in my dashboard ? Some help ?
Check that you are actually using the database by doing the following: 1 - go to cpanel, file manager, public_html, open the wp_config.php file 2 - check db creds and make sure it is actually the correct db. Everything must be exact. (IP/localhost, dbname, user, etc.) 3 - check the $table_prefix - make sure the value matches the table that holds the post/pages. (Wordpress uses $table_prefix so you can actually have multiple wordpress installs in the same database.) E.g. $table_prefix = 'wp_'; but your actual table name for posts is `site_posts` \- then that's the problem, they are different sites. If your actual table name is `wp_posts` \- then it is OK. 4 - check your users table. Does the users match what you see in admin panel? If not, the website is not stored in that database. Let's say the prefix or any of the creds is wrong - just fix it directly in wp_config.php by editing the value to match. It should work right away.
stackexchange-wordpress
{ "answer_score": 0, "question_score": 0, "tags": "database" }
Is it safe to increase/alter the size of the wp_post.guid column from VARCHAR(255) to VARCHAR(2048)? I am planning to use `External Media Without Import` plugin which, like any existing media, uses the guid column of the post table to store the URL of the media (ex: jpg etc). My DB has this column defined as VARCHAR(255) which is not enough for some HTTP URLs. Any drawback in increasing to VARCHAR(2048)? Any alternative to make this work without altering the DB? _Note: as pointed by Tom below, this is a really a limitation of that plugin which should use some other means of storing the external URL..._
**No, it is not safe** to resize columns in WP core tables, or to alter them. When you next update WordPress, the update process will alter the tables to the official table schema, truncating all your GUIDs and breaking them. _Instead, you need to contact the support route for the plugin so that they can fix this. They shouldn't be reusing GUIDs to store URLs if the URLs are going to be long. This is a bug in the plugin._ _Edit: There's a ticket on Core Trac related to this, reproducing and posting that you can replicate it and it affects you will help, as will watching/starring it<
stackexchange-wordpress
{ "answer_score": 3, "question_score": -1, "tags": "plugins, database, wpdb, media library" }
How to use _embed when using _fields? It seems that if you use `_fields` in an API request also containing `_embed`, the `_fields` filter will filter out all embeds. The following request: domain.com/wp-json/wp/v2/posts?_fields=link,title&_embed=wp:featuredmedia has no `_embedded` field, but it comes back if I remove the `_fields` filter. I also tried passing `_fields=link,title,_embedded`, but it doesn't work either.
It is not clear in the documentation, but you need to include the "_links" and "_embedded" as fields to be returned. In addition, I include the _embed parameter, as it does not require a value. As of WordPress 5.4, the resources to embed can be limited by passing a list of link relation names to the _embed parameter, though I have not had success with that when using _fields Example: domain.com/wp-json/wp/v2/posts?_fields=link,title,featured_media,_links,_embedded&_embed
stackexchange-wordpress
{ "answer_score": 14, "question_score": 7, "tags": "rest api" }
str_replace remove words from title I have a site that reviews movies (DVD/Blu-ray, etc.)So every review in a particular category will have (Blu-ray) after the title, another will have DVD and so forth. i.e. Avengers: Infinity War (Blu-ray). I want to trim the format of the disc (Blu-ray) from the page title and I have this code, but it's not working. Wasn't sure what the issue was. <span style="color: #ffffff">About <?php if (in_category('5447') ):?> <?php echo str_replace("(Blu-ray)","&nbsp;","<?php the_title(); ?>"); ?> </span> <?php endif; ?> So, in essence, I can grab the title and it will read: Avengers: Infinity War (Blu-ray) but I want it to read: Avengers: Infinity War
`the_title()` will directly output the title - for your purpose in a string manipulation, you need to use `get_the_title()` < you also have some php syntax error; try to use: <?php echo str_replace( "(Blu-ray)","&nbsp;", get_the_title() ); ?>
stackexchange-wordpress
{ "answer_score": 0, "question_score": 0, "tags": "php" }
How to use orderby with meta_query? I want to order posts by views after filtering them with meta_query by a specific meta_key. Using this query I was able to order posts by views but I was unable to order only the posts with the 'meta_key' => 'my_choices'. $args = array( 'post_type'=> 'post', 'posts_per_page'=> 24, 'meta_key' => 'wpb_post_views_count', 'orderby' => 'meta_value_num', 'order' => 'DESC', 'meta_query' => array( array( 'meta_key' => 'my_choices', 'meta_value' => '1', ) ), ); $wp_query = new WP_Query($args); $i=0; while ($wp_query->have_posts()) : $wp_query->the_post(); ++$i; Anyone know how can this be done? Thanks
You have used wrong parameters for meta_query. It should be - 'meta_query' => array( array( 'key' => 'my_choices', // not meta_key 'value' => '1', // not meta_value ) ),
stackexchange-wordpress
{ "answer_score": 2, "question_score": 0, "tags": "meta query" }
Add/remove image from navigation bar I am picking up the work from one of our developers who has left our company and applied a background on our header seen here < When you scroll down you will see the header has a orange circle in the cop right hand side. How do I get rid of this? I see in the code it has to do with uk-navbar-container but where can I edit this within wordpress? Any help is greatly appreciated!
Because there are many ways and many possibilities for adding a image to the bar. It is really hard to tell how to remove it directly. However, it looks like it is controlled in CSS and you could try the following. You may try to look for a `theme1.css` file and then search for `.uk-navbar-container:not(.uk-navbar-transparent)` You will see /* ... skipped here */ background-image: url(orange-circle2.svg); /* ... skipped here */ change to /* ... skipped here */ background-image: none; /* <--- change to none to hide the image */ /* ... skipped here */
stackexchange-wordpress
{ "answer_score": 0, "question_score": 0, "tags": "menus, css, navigation" }
Security when outputing wp_oembed_get code This is a code I have in a function.php action. It is responsible for getting and displaying an embed code. Typically there is a youtube link from $embed_link but it comes from a public form so it can contain anything: $embed_link = get_post_meta( $post_id, 'user_content_link_to_remote_video' ); $embed_code = wp_oembed_get( $embed_link[0] ); if ($embed_code): echo $embed_code; endif; Is there a risk of malicious code in there? Is this code safe? If not, how to make it safer?
`wp_ombed_get()` will only process URLs from whitelisted oEmbed providers. The list of supported providers is available here. This means the only code that can be output is embed code from those providers. These are the same providers that WordPress supports for URLs in content, or the embed block in the block editor, so you be reasonably assured that they are safe, as WordPress considers them safe enough for authors and contributors to use.
stackexchange-wordpress
{ "answer_score": 0, "question_score": 0, "tags": "functions, security, embed, oembed" }
Plugin path comes wrongly I need import css files from a folder in plugin directory to a plugin php file. I tried plugin_dir_path( __FILE__ ); <link rel="stylesheet" href="<?php echo __DIR__ . '/dahili/bootstrap.min.css'; ?>"> <link rel="stylesheet" href="./dahili/bootstrap.min.css"> but they gives wrong url. for example, in my last trying, I get this adress: < but I need this: hekim.deniz-tasarim.site/wp-content/plugins/my_post_plugin/widgets/dahili/bootstrap.min.css how to get true address? > Note: Please dont close my question because of dublicate if you dont give 100% same question because I need real solution, I am not troll.
To solve this problem, we must use `plugin_dir_url` command. For example: <?php wp_register_style( 'foo-styles', plugin_dir_url( __FILE__ ) . 'dahili/bootstrap.min.css' ); wp_enqueue_style( 'foo-styles' ); ?>
stackexchange-wordpress
{ "answer_score": 1, "question_score": 0, "tags": "plugin development, directory, paths" }
Add username and password section in WooCommerce's my account page I am using a WordPress website. In my account's registration section only the email field is showing. I want to add the username and password field too in the section. So the user can create an account in no time. And when user create an account, they receive a confirmation link on an email. I want to disable that too. For this, I don't want to install any plugin. Here is the snapshot
To show the password field on the registration page, you’ll want to uncheck/deselect this: <
stackexchange-wordpress
{ "answer_score": 0, "question_score": 0, "tags": "woocommerce offtopic" }
Buddypress function and global $bp question I have a question regarding Buddypress tweak. I can use any Buddypress function when I make a plugin without any include or require functions. How is it possible? Because Buddypress loads faster than my plugin? In addition, What does global $bp mean? Withou this global $bp, I can use any buddypress functions, so why does it need? I'm newbie to development. Thank you :)
Plugins load alphabetically by default. If Buddypress is alphbetically before your plugins folder name, then Buddypress will load first and it's functions will be available. Additionally, whatever functionality depends on another plugins you can always attach to the `plugins_loaded` hook, which fires after all plugins are finished loading. For example: /** * Runs code after plugins have finished loading * * @return void */ function prefix_plugins_loaded() { die( 'Plugins have finished loading.' ); } add_action( 'plugins_loaded', 'prefix_plugins_loaded' ); PHP Globals are common in Plugins and WordPress. The `$bp` global is simply a variable that likely holds a required object needed by the specific plugin function.
stackexchange-wordpress
{ "answer_score": 1, "question_score": 1, "tags": "plugin development, buddypress" }
How To Remove Import/Export Option From Tools? I want to give admin access to a freelancer. One plugin named controlled admin access done most of the part for me, expect it don't have option to select or deselect subtools.
You may use the hook admin_menu() and function remove_submenu_page() The solution assumed the following conditions * run it in theme functions.php, you may put somewhere else with different tweaking, but the following is proved to work in functions.php * you know how to test the user access level by yourself, because the following solution is focus on removing the submenu only function q364011_remove_tools_menu() { // you may add your access rights checking logic here with conditions and then do the following remove_submenu_page( 'tools.php', 'export.php' ); remove_submenu_page( 'tools.php', 'import.php' ); } add_action( 'admin_menu', 'q364011_remove_tools_menu' );
stackexchange-wordpress
{ "answer_score": 0, "question_score": 0, "tags": "admin, user access" }
How can I remove a button from the paragraph block toolbar? I want to remove the **bold** option from the toolbar in the wordpress paragraph block. I did not find any documentation on that. The closiest thing I found was a tutorial to add buttons. ![remove bold button from toolbar]( Any help would be appreciated.
> I want to remove the bold option from the toolbar in the wordpress paragraph block. At the moment, it cannot be done, the paragraph block doesn't use the format API but instead hardcodes the markup for those buttons in the toolbar component You could: * strip out the bold tags on save in PHP * hide the button using CSS * Add a CSS editor style so that the font weight of bold text is the same as unbolded text * Open a feature request on the GitHub repo for Gutenberg But: * These won't prevent the bold shortcut of cmd+b * Users can still use markdown shortcuts by writing `*bold text*` * Users can also write the bold text somewhere else, then copy paste it into the paragraph block
stackexchange-wordpress
{ "answer_score": 1, "question_score": 2, "tags": "block editor" }
Get rewrite slug of custom post type in template How do I get the rewrite slug of a custom post type inside a template? register_post_type( 'products', 'rewrite' => array( 'slug' => 'fabrications' ), // ... etc ); Now inside my template file inside the `global $post` there is post_type property. But I can't find the `rewrite slug` anywhere. Please help. **Update:** I needed this for permalinks inside a template part where there are categories displayed. <a href="<?php echo get_site_url() . '/' . $post_type_slug . '/category/' . $category->slug . '/' ?>" class="cat-bar__label"><?php echo $category->name; ?></a>
You can access the post type properties using `get_post_type_object()`. The rewrite argument will be a property if the returned object: $post_type_object = get_post_type_object( 'products' ); $rewrite_slug = $post_type_object->rewrite['slug']; * * * **Update** > I needed this for permalinks inside a template part where there are categories displayed. No you don't. To get the URL to a category archive, use `get_term_link()`: <a href="<?php echo esc_url( get_term_link( $category ) ); ?>" class="cat-bar__label"><?php echo $category->name; ?></a>
stackexchange-wordpress
{ "answer_score": 2, "question_score": 1, "tags": "custom post types, php, plugin development, customization" }
Modify YouTube Embed Code to fit theme I'm using a custom bootstrap template and other users will be embedding youtube videos, which I want to be responsive to fit the theme. What can I do to make the normal YouTube embed code, something like this: <iframe width="560" height="315" src=" frameborder="0" allow="accelerometer; autoplay; encrypted-media; gyroscope; picture-in-picture" allowfullscreen></iframe> Into this formatting (simplified and with class added): <iframe class="embed-responsive-item" src=" allowfullscreen></iframe> Any help would be fab!
If you're using the block editor, the fix is simple: add_theme_support( 'responsive-embeds' ); You can also make the iframe responsive using pure CSS, just wrap it in a `div`: <div class="yt-container"> </div> .yt-container { position:relative; padding-bottom:56.25%; padding-top:30px; height:0; overflow:hidden; } .yt-container iframe, .yt-container object, .yt-container embed { position:absolute; top:0; left:0; width:100%; height:100%; } This article covers making embeds responsive using CSS and JS: <
stackexchange-wordpress
{ "answer_score": 1, "question_score": 0, "tags": "twitter bootstrap, embed, responsive, youtube" }
How to write files in hosting in admin dashboard? I see that some plugins like Wordfence can write on core folders like `wp-includes` or `wp-admin` (if write permission is enable). In case everything is permitted, is there a way to interact with the hosting from admin dashboard only? Assuming this is on the site installation folder only. See also: • Is there a way to figure out the way to access hosting if I have admin privilege? • WordPress file manager plugin that can change file permission? in Software Recommendations
You basically have two options: 1. Use any of the available File Manager plugins for WordPress. Just Google them, literally that phrase I just used. 2. Implement a custom PHP code in your theme or custom plugin which will utilize any of the PHP functions for manipulating the files. For example, check these: * `file_get_contents()` \- For reading files * `file_put_contents()` \- For writing files. This will also create a new file if it doesn't exist. * `unlink()` \- For deleting files * `chmod()` \- For changing permissions * `chown()` \- For changing owner There are also a ton of functions for more advanced file manipulation in PHP. Check this for reference: Filesystem Functions
stackexchange-wordpress
{ "answer_score": 4, "question_score": 2, "tags": "dashboard, hosting, user interface" }
White page by using filter template_include I working on my plugin and tried to override some templates. If I visit the page portfolio my screen gives a whitepage. This is my code define("PLUGIN_DIR_PATH", plugin_dir_path(__FILE__)); add_filter( 'template_include', 'plugin_tweak_template', 99); function plugin_tweak_template( $template ) { if ( is_page('portfolio')) { $template = PLUGIN_DIR_PATH . 'required/templates/portfolio.php'; } return $template; } I use this code in my plugin root file.
The white screen means that you have a critical error that is halting execution, but you do not have PHP messaging turned on to tell you what that error is. Turn on debug mode in WordPress so the error message is displayed. Otherwise you don't have enough information to correct your problem. Set the `WP_DEBUG` constant in your `wp-config.php` file to `true`. See: Debugging in WordPress Once you know what that error is, you can edit your question with more information.
stackexchange-wordpress
{ "answer_score": 0, "question_score": 1, "tags": "plugins, plugin development, filters" }
How to set default post editor based on role? I found this code to functions.php add_filter( 'wp_default_editor', create_function('', 'return "html";') ); but I need to limit it to a specific set of roles (such as Editor or Author). How do I do that? Thanks!
`create_function()` is deprecated as of PHP 7.2.0, so you should avoid using it. Instead, use an anonymous function. Additionally, it's better the check the current user role _inside_ the callback function, so that the current user role is checked when the filter is applied, not when the hook is added, which could be before the current user role can be determined. add_filter( 'wp_default_editor', function( $default_editor ) { if ( current_user_can( 'editor' ) || current_user_can( 'author' ) ) { $default_editor = 'html'; } return $default_editor; } );
stackexchange-wordpress
{ "answer_score": 2, "question_score": 0, "tags": "functions, user roles, editor" }
One file for all translations Is there any solution to translate just specific strings from plugins/theme from one central file? So the only translated strings are there (frontend) so editor of the website doesn't need to search trough all .MO files in Loco translate for example?
**No, this isn't possible, that's not how`mo` or `po` files work.** A `po` file declares which locale it is for, and gets compiled into an `mo` file. You can't store more than 1 locale in the same file. Each file represents a single locale. Keep in mind that these files aren't a WordPress thing. They're a `gettext` thing, and are used in lots of different applications, including other CMS's and even programs that have nothing to do with websites and servers. So there is no WordPress based solution to your problem. Your search should continue elsewhere, specifically in the area of tooling
stackexchange-wordpress
{ "answer_score": 2, "question_score": 0, "tags": "plugins" }
Rewrite URL for only archive page (custom post type) There is a few Q/A about custom post URL rewrite but I haven't found any simple answer to what I'm trying to achieve. My CTP is "event" and **I have the current page structure that I want to preserve** : * `siteurl.com/agenda` * `siteurl.com/event/event-slug` Right now in my theme I use two files `single-event.php` and `page-agenda.php`. The latter is the archive page, because I want my archive post slug to be `siteurl.com/agenda` and not `siteurl.com/event` so I've created an additional page on my backend. It's working like that but I'd like to know if there is a more elegant solution to only rewrite my CPT archive page URL while using the proper `archive-event.php` template?
You can have a separate slug for the post type archive by setting the slug as the value for the `has_archive` argument, instead of just `true`: register_post_type( 'event', array( 'has_archive' => 'agenda', // etc. ) ); Now you can use `single-event.php` and `archive-event.php` for the single and archive views, but the URL for the archive will be `siteurl.com/agenda`.
stackexchange-wordpress
{ "answer_score": 4, "question_score": 2, "tags": "custom post types, url rewriting, template hierarchy, archive template" }
Change sign up fee in cart for subscription products WooCommerce i am changing the price of products in cart like this add_action('woocommerce_before_calculate_totals', 'set_custom_price',1000,1); function set_custom_price($cart_obj) { foreach ($cart_obj->get_cart() as $key => $value) { if($value['alredy_have_number'] == true) { $value['data']->set_price(0.90); } } } It works fine for recurring price but I wants to change signup fee for subscription products. what function or hook can I use for that ?
add_action( 'woocommerce_before_calculate_totals', 'change_subscription_signup_fee', 1000, 1 ); function change_subscription_signup_fee( $cart ) { if (is_admin() && !defined('DOING_AJAX')) return; if ( did_action( 'woocommerce_before_calculate_totals' ) >= 2 ) return; // Loop through cart items foreach ( $cart->get_cart() as $cart_item ) { // Check that product custom cart item data "alredy_have_number" exist and is true if( isset($cart_item['alredy_have_number']) && $cart_item['alredy_have_number'] ) { // Check if subscription products if ( in_array( $cart_item['data']->get_type(), ['subscription', 'subscription_variation']) ) { // Change subscription Sign up fee $cart_item['data']->update_meta_data('_subscription_sign_up_fee', 0.90); } } } }
stackexchange-wordpress
{ "answer_score": 1, "question_score": 1, "tags": "php, woocommerce offtopic, subscription" }
Do not change the order of the tags in the editor I have a list posts by tag, but the relation is not relevant because first look for the posts with the first tags stored alphabetically, and not the first main tag, that is to say for me the order of the tags are key because the first tag is the most relevant. So when saving everything, it is sorted alphabetically and this does not help me, any idea how to alter this? ![screenshot](
**Terms/Tags aren't ordered**. To help make the terms easier to read, the editor will list them alphabetically, but that isn't because they're ordered alphabetically in the database. It's because a piece of javascript sorted the terms in the UI control. There is no order, only the order you give them. Fundamentally terms have no order. Any order you see in the editor is purely circumstantial, there is no order mechanism in the database for terms. If you want to give special meaning to a term, you need to do so explicitly, e.g. store the term ID of the significant term in post meta. You cannot rely on order, as terms do not have order.
stackexchange-wordpress
{ "answer_score": 2, "question_score": 1, "tags": "tags, block editor, editor" }
How do I see the mysql query generated by get_posts( $args )? I'm trying to use get_posts( $args ) to get some custom post types. Is there a way to see the mysql query generated by the get_posts function?
Thank you to Tom J Nowell for pointing me to using `WP_Query` instead of `get_posts`. With WP_Query you have the entire `WP_Query` object to reference. So something like the following gives the actual mysql query of the args I was using. // these same args also worked with get_posts() $args = array( 'post_type' => 'post', 'order' => 'ASC', 'post_status' => 'publish', ); // create a new WP_Query object with the args above $the_object = new WP_Query($args); // show the mysql as a string echo $the_object->request; // see EVERYTHING in the WP_Query object var_dump($the_object);
stackexchange-wordpress
{ "answer_score": 0, "question_score": 1, "tags": "query, mysql, get posts, sql" }