INSTRUCTION
stringlengths
11
999
RESPONSE
stringlengths
0
999
SOURCE
stringlengths
16
38
METADATA
dict
Field has disappeared on post page I have taken over a site from someone. He has a list of businesses on the site, each one has a URL, saved as a field: `$iframe_url = get_field(‘manufacturer_url’);` It seems he used to manage this URL on a custom post-type page, but the actual field to edit the URL has disappeared – maybe in some recent WordPress update. I have made sure on the edit page, all the elements are checked off on the ‘screen options’ tab. But i still cannot see where this field is, where i can change the URL. Any ideas? Using Version 5.8.7 of the plugin WP version: WordPress 5.1.4 running Chameleon-Child theme.
Followup for any future questioner. It seems like the Field Group of ACF had been deleted. As soon as i created a new group and field named `'manufacturer_url'` the fields all became accessible again. Thank you.
stackexchange-wordpress
{ "answer_score": 0, "question_score": 0, "tags": "advanced custom fields" }
get_post_meta returns empty array for terms I have custom post type of jobs and in this post type I have two custom taxonomies. For job post I selected few terms from both these taxonomies in admin panel but when I tried to access these on front end using `get_post_meta`it is displaying these terms as empty. I have two taxonomies (city, industry). I am getting city terms like this [_job_city] => Array ( [0] => ) I am getting industry terms like this [_company_industry] => Array ( [0] => s:1:"1"; ) Any suggestion ?
Instead of `get_post_meta` now I am using `wp_get_post_terms` function to access job post terms and it is working for me. It is working correctly for both these taxonomies.
stackexchange-wordpress
{ "answer_score": 1, "question_score": 1, "tags": "custom post types, custom taxonomy, terms" }
Adding buttons to Add New Post and Add New Page I want to add a button in Add New Page and Add New Post pages. Here are places I want to add items: * New page's sidebar (next to Page Attributes). * New post's sidebar (next to Post Attributes). * New page's top bar (next to Block Navigation). * New post's sidebar (next to Block Navigation). What are the action hook to do it so? function add_new_button_function (???) { echo "some html code"; } add_action( '???', 'add_new_button_function' );
Welcome! Here is a documentation for adding Custom sidebar. You can check possibilities and sample codes to add new metaboxes or buttons.
stackexchange-wordpress
{ "answer_score": 0, "question_score": 1, "tags": "posts, customization, pages, hooks, actions" }
Admin pages, edit notes of the title of posts and pages Here is a screenshot of the admin console pages I find here a description of the page on the title column (marked in RED), I would like to add such notes on pages I create or edit the ones already there. I can't find it on the edit screen or any other related editable part. Can anyone help me?![enter image description here](
Welcome! Those areas you have marked with a red border is called **Post states**. In order to modify post states you can use `display_post_states` filter. The following example adds the post id to states. function my_custom_display_post_states( $states, $post ) { // Add post id. $states['my_custom_state'] = $post->ID; return $states; } add_filter( 'display_post_states', 'my_custom_display_post_states', 10, 2 );``` Please check WordPress documentation for more information.
stackexchange-wordpress
{ "answer_score": 0, "question_score": 1, "tags": "pages, admin" }
Group listed elements by category I'm quite new to wordpress so there's a lot of terms I'm missing... I'd like to have a list of elements, grouped depending on a category. For example, let's say I have a list of superhero movie names, I want the user to be able to group them either by hero or by franchise. It would look like this: grouped by hero: Iron Man -Iron Man 1 -Iron Man 2 -Iron Man 3 Thor \- Thor 1 \- Thor 2 Grouped by franchise: MCU \- Iron Man 1 \- Thor 1 ... DCEU \- Batman 1 \- Superman 1 ... I have no idea if there are plugins or controls to help with this, don't know even how to look for the terms. The solution I was thinking of was to somehow assign to each movie a series of metadata tags, e.g.: to Iron Man 1 give it "hero:ironman", "franchise:mcu", "starring:rdjunior". And then pull from there, but it sounds quite convoluted... Thanks in advance!
The term you are looking for seems to be "Taxonomy", category and post_tag are base taxonomies, but you can register more taxonomies, depending on the needs. Right now, you are in need of 2 taxonomies, "hero" and "franchise", once registered, you can affect them to a range of post_type. I don't know if your "movie" is a CPT (Custom Post Type), but it should probably be. (Edit) Forgot to give you some link in the Codex: <
stackexchange-wordpress
{ "answer_score": 1, "question_score": 1, "tags": "categories, plugin list category post" }
Could a user account with a stolen password compromised entire WP site? Assuming a user with Subscriber role account with a weak password has been hacked. So, can someone use this account to compromise a WP site?
Any subscriber can't do any harm to your site even if he wants it. <
stackexchange-wordpress
{ "answer_score": -1, "question_score": 0, "tags": "security, password, hacked" }
Can you edit a theme in a text editor? I'm developing a custom theme on my local machine (running macOS). I'd like to edit it in my favorite text editor instead of in the browser via the Theme Editor. Is there a way to do this? Since I'm working locally, I was thinking there might be a way to do this without going over FTP, such as editing the files directly. My dev server is Local/Flywheel.
When you install your theme via the WordPress admin panel, it's just decompressing the ZIP file and placing the contents in a directory. For me, using Local as a dev server, that location was `~/Local Sites/<my-site-name>/app/public/wp-content/themes/<my-theme-name>`. You can edit those files directly and the changes will be reflected when you refresh your browser.
stackexchange-wordpress
{ "answer_score": 0, "question_score": 0, "tags": "theme development" }
Look up all posts by status or meta value - performance difference Anyone know if there is likely a big performance difference to these two queries? 1. get all posts by status = TRASH 2. get all posts which have the meta key `_delete_product` and has a value of TRUE I will be doing a nightly cron purge of all posts which are to be deleted. Best thing is to grab all relevant posts in the most efficient way possible here before looping through them.
As mentioned in the comments, `post_status` is stored in the posts table but postmeta values are stores in postmeta table which is usually a much more heavy table than posts. Using a meta in db queries, results in adding a JOIN clause to the query to join this heavy table! So using `post_status` is definitely a better performance choice.
stackexchange-wordpress
{ "answer_score": 2, "question_score": 0, "tags": "post meta, get posts" }
Best way of getting WooCommerce category path If I am on a product or any category/subcategory I want to display a complete path to the topmost category. Does WooCommerce already have a function for it or do I need to make my own loop that goes from child to parent? Should I use $wp_query->get_queried_object()? What is the best code for it? Example: ![enter image description here](
I think you may look for breadcrumb? Can you try it? <?php woocommerce_breadcrumb(); ?> This link may help: <
stackexchange-wordpress
{ "answer_score": 0, "question_score": 1, "tags": "categories, woocommerce offtopic" }
Correctly using the root directory for media uploads? I am aware what I'm attempting to do is not recommended - please don't reply just to tell me this. I have set the uploads directory to root by adding `define( 'UPLOADS', '' );` to `wp-config.php`, which works fine except the URLs for my uploads end up with a double slash (` The address I've defined for my website in the General settings does not have a trailing slash. While this doesn't break anything, it looks a little peculiar in the event anyone copies the URL, so it would be preferable to resolve. So far I've tried using an absolute URL as per this answer (doing so just results in ` and inserting a backspace character as per this answer, which was a bit of a longshot.
The WordPress uploads directory's path and URL are determined by the `wp_upload_dir()` function which applies a filter named `upload_dir` which you can use to fix the double slashes in the attachment URL. So if you turned off the "Organize my uploads into month- and year-based folders" setting, try the following: add_filter( 'upload_dir', function ( $data ) { $data['baseurl'] = untrailingslashit( $data['baseurl'] ); return $data; } ); And you can actually use the `upload_dir` filter to change the uploads directory path/URL/etc. without having to use the `UPLOADS` constant..
stackexchange-wordpress
{ "answer_score": 1, "question_score": 0, "tags": "uploads, media library" }
Adding JavaScript file in Admin Panel I am learning WordPress plugin development. I am trying to attach a jQuery/JavaScript file in Admin Panel. I am using below code in plugins `index.php` file. function admin_script() { wp_enqueue_script('my_custom_script', plugin_dir_url(__FILE__) . '/myscript.js'); } add_action('admin_enqueue_scripts','admin_script'); Is it correct code ? What is `my_custom_script` here?
Yes, your code is good. And that `my_custom_script` is a unique identifier for the script you're enqueueing. You can find the default script handlers/identifiers here — e.g. `jquery` for the jQuery library that ships with WordPress. There you can also find more details about the `wp_enqueue_script()` function, e.g. where should you use the function, the parameters, etc.
stackexchange-wordpress
{ "answer_score": 1, "question_score": 0, "tags": "jquery, wp admin, hooks, actions" }
hide page menu from admin panel for specific users I want to hide page menu from the admin panel for a specific user type. I tried it with the below codes in `functions.php` function hide_menu_items() { global $menu; global $current_user; get_currentuserinfo(); if( $current_user->user_login == 'username' ): remove_menu_page( 'admin.php?page=megamenu' ); remove_menu_page( 'admin.php?page=mycustompage' ); endif; } add_action( 'admin_menu', 'hide_menu_items' ); It's not working but it only hides post_types
I fix my problem using below codes: function hide_admin_menu() { global $menu; global $current_user; get_currentuserinfo(); if ( $current_user->user_login == 'username' ) { remove_menu_page( 'megamenu' ); remove_menu_page( 'mycustompage' ); } } add_action('admin_menu', 'hide_admin_menu', 999); Just add page name to remove the page from specific users
stackexchange-wordpress
{ "answer_score": 0, "question_score": 0, "tags": "users, user roles, admin menu, sub menu" }
How to display featured image description and title? I'm displaying a featured image (as a background) in a hero div, and using the caption to add some content from the Media Library automatically. I'd also like to use the image's description field and title, but can't find documentation on that. Here's what I have so far, which works as expected: <div class="hero"> <?php $thumb = wp_get_attachment_image_src( get_post_thumbnail_id($post->ID), 'full' );?> <div class="hero-image" style="background-image: url('<?php echo $thumb['0'];?>')"></div> <div class="hero-content"> <h1>NEED IMAGE DESCRIPTION HERE</h1> <p class="caption"><?php get_the_post_thumbnail_caption(); ?><?php the_post_thumbnail_caption(); ?></p> </div> </div> I'm not sure if I'm already getting that info, but not echoing it...or if I need to do more to get it from the database. Thanks in advance for your help!
this might work: `$post_thumbnail_id = get_post_thumbnail_id($post->ID); $thumbnail_image = get_posts(array('p' => $post_thumbnail_id, 'post_type' => 'attachment')); if ($thumbnail_image && isset($thumbnail_image[0])) { $img_description = $thumbnail_image[0]->post_content; $img_caption = $thumbnail_image[0]->post_excerpt; $img_alt = get_post_meta($post_thumbnail_id , '_wp_attachment_image_alt', true); $img_title = $thumbnail_image[0]->post_title; }`
stackexchange-wordpress
{ "answer_score": 1, "question_score": 0, "tags": "post thumbnails, title, description" }
I wan redirect link post search to search product woocommerce? Search results link for the post : < I want when clicking search, the article search link automatically redirects to the product woocommerce search link is: We hope you help, thank you !!!
> I think, you just need to add below code on above the submit button code in `searchform.php` file. <input type="hidden" name="post_type" value="product" />
stackexchange-wordpress
{ "answer_score": 0, "question_score": 0, "tags": "woocommerce offtopic, search" }
set_transient fails if the value has more than 60.000 characters I have a problem which I can't figure out. I have a collection of object which sometimes can be very big. I have to store the entire collection as a serialized transient. The problem is that when the serialized string has more than 60000 characters the insertion in the DB fails. Why? I checked the wp_options table and the "value" column is a longtext. Which holds 4GB of data, am I right?
I found the problem! Everything was ok with the transient, the problem was that I'm using php's substr() to cut an object property value if exceeds maximum characters. When in that string there was an accented character there was a problem with the encoding. So the serialized collection had an encoding issue at character 60000... I fixed it using substr_mb() and specifying UTF-8 as encoding. Hard to debug this issue since wpdb doesn't throw any error when there is an encoding problem.
stackexchange-wordpress
{ "answer_score": 0, "question_score": 0, "tags": "database, transient" }
How do I set is_active_sidebar? I have a Page like: <?php /* Template Name: Agenda */ get_header(); ?> <div class="wrap"> <div id="primary" class="content-area"> <main id="main" class="site-main" role="main"> My Hompagetext </main><!-- #main --> </div><!-- #primary --> <?php get_sidebar('test'); ?> </div><!-- .wrap --> <?php get_footer();?> I have a sidebar called: sidebar-test.php <aside id="secondary" class="widget-area" role="complementary" aria-label="<?php esc_attr_e( 'Test Sidebar', 'rczo2' ); ?>"> this text is displayed on the bottom but I want it in the sidebar on the right side </aside><!-- #secondary --> I tryed reading across the WP-documentation and found how to register a widget, but not how to include a simple script like this.
I had to add: <body <?php body_class('has-sidebar'); ?>> to the header of my Page
stackexchange-wordpress
{ "answer_score": 0, "question_score": 0, "tags": "sidebar" }
How to remove all plugins, posts, pages, and inactive themes in one line with wp-cli? WordPress bloatware removal Softaculous seems to always adds junk to the installs I don't want. Such as example posts, pages, plugins, and starter themes. How do I remove them all for a fresh start?
I'd love any improvements, or hopefully this helps someone. wp post delete $(wp post list --post_type='post' --format=ids);wp post delete $(wp post list --post_type='page' --format=ids);wp plugin delete --all;wp theme delete $(wp theme list --status=inactive --field=name);wp widget delete $(wp widget list sidebar-1 --fields=id);wp widget delete $(wp widget list sidebar-2 --fields=id) edit: added removal of default widgets in sidebar, all seems to work now!
stackexchange-wordpress
{ "answer_score": 0, "question_score": 0, "tags": "linux, command line, php" }
WooCommerce Hook after Billing form completed, but before payment Gateway In Woocommerce, I need to call a function after than the client completed the billing form, but before the payment gateway. This function needs to use the billing form informations... Is there a Hook for that, and how can I retrieve the users infos ?
This action hook is performed after submission: add_action( 'woocommerce_thankyou', 'custom_woocommerce_auto_complete_order' ); function custom_woocommerce_auto_complete_order( $order_id ) { echo $order_id; }
stackexchange-wordpress
{ "answer_score": 0, "question_score": -1, "tags": "woocommerce offtopic, hooks" }
Visualize info in just custom post_type in theme So in a local wordpress I created a plugin that will make a row with its custom post type called book (it is saving successfully in the db)... and now I want to display a special template for it in the index of my theme, but after I use this code nothing shows: <?php $loop = new WP_Query( array( 'post_type' => 'book', 'category_name' => 'book', 'ignore_sticky_posts' => 1, 'paged' => $paged ) ); //// if($loop->have_posts()): while ( $loop->have_posts() ) : $loop->the_post(); ?> <div class="ptitle"> <h2><?php echo get_the_title(); ?></h2> </div> <h3> <?php the_title(); ?> </h3> <small>Posted on:<?php the_time('F j, Y'); ?>, in <?php the_category(); ?> </small> <p> <?php the_content(); ?> </p> <hr> <?php endwhile; endif; ?>
The loops itself is working. I guess you have trouble to output this content on some page template. There are many ways how to show output of this loop on the homepage. 1.You can create `home.php` file, put there your code and in theme settings select which page should output your custom post type. 2.You can create page template according to the documentation, put there your code, create some page in wordpress admin and on the right side in editor menu choose your newly created template.
stackexchange-wordpress
{ "answer_score": 0, "question_score": 0, "tags": "custom post types, php, theme development, localhost" }
Restrict wordpress access to logged users only I want to limit the access to a wordpress app only to registered users. I've putted this inside the function file, but I'm able to see the home also if I'm not logged in. How I fix this? if( is_home() || is_page() || is_single() && !is_user_logged_in() ){ wp_safe_redirect( wp_login_url() ); }
This works only for blog pages, pages, and single posts. You need to disable redirection on the login page. Here you can find how to detect the login page. Check if wp-login is current page So to redirect globally as you want use: if(!is_user_logged_in() && !is_wplogin() ) wp_safe_redirect( wp_login_url() ); Function is_wplogin() is from here: < I also prefer to do redirection after init: function is_wplogin(){ $ABSPATH_MY = str_replace(array('\\','/'), DIRECTORY_SEPARATOR, ABSPATH); return ((in_array($ABSPATH_MY.'wp-login.php', get_included_files()) || in_array($ABSPATH_MY.'wp-register.php', get_included_files()) ) || (isset($_GLOBALS['pagenow']) && $GLOBALS['pagenow'] === 'wp-login.php') || $_SERVER['PHP_SELF']== '/wp-login.php'); } add_action('init', function () { if (!is_user_logged_in() && !is_wplogin()) { wp_redirect(wp_login_url()); die(); } });
stackexchange-wordpress
{ "answer_score": 0, "question_score": 0, "tags": "php, functions, login" }
Template Hierarchy for custom post type pages So I have a custom post type that is called `recipe` and then I have a page called `/recipes/` \- What would be the proper way to hook a template for my recipes page? I have the file `single-recipe.php` following the WordPress hierarchy with this inside: <?php /* Template Name: Recipe Template Post Type: post, page */ echo 'Hello'; But I'm not getting any templating output: ![enter image description here]( The below is my folder structure: ![enter image description here](
The filename `single-recipe.php` is telling WordPress "only use this file to display single 'recipe' CPT posts." If you want to use it as a Page template, you can either rename the file `tpl-recipe.php` (or something similar, it doesn't have to be this filename, it just has to not be a recognized pattern like `single-cptslug.php`) - in which case you'll have to manually choose that template every time you create a new Recipe - Or, you can have two files. One named `single-recipe.php` which does NOT have the comments at the top, and one named `tpl-recipe.php` (or similar) which DOES have the comments at the top.
stackexchange-wordpress
{ "answer_score": 1, "question_score": 0, "tags": "custom post types, theme development, themes" }
How to put a contact form inside the footer of all the articles and pages of a website? I have a Contact Form 7 form inside a WP website. I want to insert this form at the end of every page and article of the website, near the copyright notice. I just know the short code of the form (it works well inside a specific post): [contact-form-7 id="42" title="Formular de contact"] Having the short code I think that the question is not off-topic. I have basic knowledge of PHP and JavaScript. I have searched Google a little and I still do not know how to do this. Thank you.
You can add contact form shortcode in footer.php via use do_shortcode <?php echo do_shortcode('[contact-form-7 id="42" title="Formular de contact"]') ?>
stackexchange-wordpress
{ "answer_score": 1, "question_score": 0, "tags": "plugin contact form 7" }
Error messages in Multilingual part of the site The english part of our viking-realestate.com site is working perfectly, but we are suddenly getting the following error messages on the german part: What could be the issue? Warnung: sprintf (): Zu wenige Argumente in /home/ewjsbqew/public_html/wp-content/plugins/js_composer/config/containers/shortcode-vc-row.php online 184
Please check your plugin compatibility with your theme. I think it's happening for an update. Plugin may be outdated.
stackexchange-wordpress
{ "answer_score": 0, "question_score": 0, "tags": "plugins" }
WP Coding standards - escaping the inescapable? How do you escape these two examples? `wc_price()` wraps the already escaped `$product_price` in `p` and `span` tags with currency symbol. $product_price = $product->get_price(); <p><?php echo wc_price( esc_html( $product_price ) ); ?></p> The next one outputs the complete image with all attributes: `src`, `srcset`, `alt`, etc. $product_img = $product->get_image(); <?php echo $product_img; ?>
For the first example, a lot of people will use wp_kses_post to handle basic HTML output from wrapper functions. It's a shortcut for some basic attributes and tags using wp_kses. You could use this function where you specify allowed tags and attributes that can pass through for the second example.
stackexchange-wordpress
{ "answer_score": 2, "question_score": 3, "tags": "sanitization, coding standards" }
How to associate custom taxonomy terms with custom post type? how to associate custom taxonomy terms with post type insert into wp_term_relationships table.
$catids = $_POST['artticle_category']; /* * If the ids are coming from the database or another source, we would * need to make sure these were integers or convert them to interger using intval: */ $catids = array_map( 'intval', $catids ); $catids = array_unique( $catids ); $taxonomy = 'articles_category'; $post_id = '1'; $term_taxonomy_ids = wp_set_object_terms( $post_id, $catids , $taxonomy );
stackexchange-wordpress
{ "answer_score": 0, "question_score": 0, "tags": "custom post types, custom taxonomy, terms" }
Combine two filters into a single call Is it possible to combine two filters? add_filter( 'manage_edit-post_columns', function($columns) { $columns['author'] = 'User'; return $columns; }); add_filter( 'manage_edit-recipe_columns', function($columns) { $columns['author'] = 'User'; return $columns; }); I want to rename the 'author' column on all pages with posts; but I don't want to apply it to every single custom post type.
As long as the received arguments and the return values are the same, yes, you can combine them. add_filter( 'manage_edit-post_columns', 'my_columns_callback' ); add_filter( 'manage_edit-recipe_columns', 'my_columns_callback' ); function my_columns_callback( $columns ) { $columns['author'] = 'User'; return $columns; }
stackexchange-wordpress
{ "answer_score": 1, "question_score": 1, "tags": "php, filters" }
Getting RGBA colour from gutenberg colourpicker I'm working on a block that has it's own colour picker. This is working fine and I can see my background colour changing however I'm only able to get the hex value for the colour. I'm changing the colour as it stands by doing:- style={{ backgroundColor: `${tint.hex}` }} Tint is an object returned from the colour picker and I can see that it has a sub object called color that contains rgba values. How do I get these values and make the backgroundColour use rgba()?
If you mean `wp.components.ColorPicker` which is based on _react-color_, then the `tint` object also contains a `rgb` property with an object of the RGBA value like `{r: 51, g: 51, b: 51, a: 1}`. So in your code, you can use: style={{ backgroundColor: `rgba(${tint.rgb.r}, ${tint.rgb.g}, ${tint.rgb.b}, ${tint.rgb.a})` }} And an easy trick to know all the available properties in the color object is by running `console.log( tint )`.. :)
stackexchange-wordpress
{ "answer_score": 2, "question_score": 1, "tags": "plugins, block editor, variables" }
New bulk action to resend welcome emails I have added a new custom bulk action to the user listing page called Resend Welcome Email, it is showing and running. What I'm looking to do is fire the Resend Welcome Email plugin's action. I'm struggling to implement this... I have tried to use the add_action call of: add_action ( 'resend_welcome_email', 20, $user ); But nothing seems to happen. It is possible to fire a plugin's action via this method? Is that how add_action works? What I'm looking to do is talked about here but I can't figure out how to action what the plugin author is talking about. Thanks, Adam
I don't think the plugin is helpful for your case, and you can just call the WordPress API yourself directly: wp_new_user_notification( $user_id, null, 'both' ); This is all the plugin does: get's the user ID from request parameters, verifies the user exists and then calls wp_new_user_notifications (see plugin code here).
stackexchange-wordpress
{ "answer_score": 1, "question_score": 0, "tags": "plugins, actions" }
Create category after theme setup and modify the default one I need to modify the default category that is created by wordpress after the installation. I want to create a new one and modify the existing one after that my theme is activated. Is this possible?
You can use wp_update_term to modify terms (even the default uncategorized) and wp_insert_term to update existing terms. Here is a basic example that should get you there. function add_category(){ // Update Uncategorized Category (1) wp_update_term( 1, 'category', array( 'name' => 'New Category Name', 'slug' => 'new-category-slug' ) ); // Insert New Category if(!term_exists('another-category')) { wp_insert_term( 'Another Category', 'category', array( 'slug' => 'another-category' ) ); } } add_action('after_setup_theme', 'add_category'); This is tested and works.
stackexchange-wordpress
{ "answer_score": 0, "question_score": 0, "tags": "php, categories, theme development, terms" }
Disable Cloudflare Rocket Loader for jQuery javascript and make it load first I use Cloudflare Rocket Loader to speed up Javascript on my site. The problem is, it loads certain scripts that need jQuery before loading jQuery itself making them not working correctly. As soon as it is possible to disable Rocket Loader for specific script adding `data-cfasync="false"` to the `<script src="">` I would like to know how can I add it to jQuery scripts as Wordpress doesn't simply load the jQuery via the script tag I guess. At the moment my website loads **jquery-migrate.min.js** and **jquery.js** PS there is a similar question but it's almost 7yrs ago so, it may be outdated at this point Cloudflare's Rocket Loader + Wordpress -> Ignore scripts?
jQuery is loaded by WordPress with `wp_enqueue_script`. The problem is Wordpress also use the below code to change the `handle` public function localize( $handle, $object_name, $l10n ) { if ( 'jquery' === $handle ) { $handle = 'jquery-core'; } The solution is to use the function function wpse_script_loader_tag( $tag, $handle ) { if ( 'jquery-core' !== $handle ) { return $tag; } return str_replace( ' src', ' data-cfasync="false" src', $tag ); } add_filter( 'script_loader_tag', 'wpse_script_loader_tag', 10, 2 );
stackexchange-wordpress
{ "answer_score": 1, "question_score": 0, "tags": "jquery, javascript, scripts" }
how to embed or share a gits in my blog wordpress? I am new in worpdress but I would like to share my code gits in my blog wordpress. so then I made a gits in github: (this code it is just a example for this question) ![done]( but when I try to share my gits in wordpress I got this: ![error]( does anyone know how I can fix that and share my code in wordpress? note:** my blog wordpress is in a hosting web i dont use the platform from wordpress I have installed the wordpress in my blog. **
In your screenshot, there's an **Embed** option with `<script>` tag in it. Take that code and add it to a _Custom HTML_ block.
stackexchange-wordpress
{ "answer_score": 2, "question_score": 0, "tags": "github" }
Is there documentation for objects returned by WP_Query? I'm running a cusotm `WP_Query` to get a handful of posts based on some parameters. Once I have the posts and I'm looping over them, I need to extract certain metadata elements, such as a list of tags for the post. I see there's a function `get_the_tags` for fetching an array of "tag objects", but I'm not seeing any references to where those are documented (i.e. what properties/methods do the tag objects have?)
The tag objects returned by `get_the_tags()` use `WP_term` class. You can see this by inspecting the function's source. The class is mentioned on the last line of the comment. function get_the_tags( $id = 0 ) { /** * Filters the array of tags for the given post. * * @since 2.3.0 * * @see get_the_terms() * * @param WP_Term[] $terms An array of tags for the given post. */ return apply_filters( 'get_the_tags', get_the_terms( $id, 'post_tag' ) ); }
stackexchange-wordpress
{ "answer_score": 0, "question_score": 0, "tags": "wp query" }
Wordpress email could not be sent I have faced an error while forgetting email password in WordPress link : `/wp-login.php?action=lostpassword` After submitting email faced below errors: ERROR: The email could not be sent. Your site may not be correctly configured to send emails.
The most common reason for this is that your WordPress hosting server is not configured to use PHP mail() function. How to configure your mail with wordpress and here is smtp plugin link
stackexchange-wordpress
{ "answer_score": 1, "question_score": 0, "tags": "email, wp mail" }
Why is my custom template not showing anything? **UPDATE 1:** I tried creating a new page and the header and footer is showing, but not the posts. **UPDATE 2:** If I update the Reading settings to Post page and select the page I created with the custom template, nothing is showing. <?php /* Template Name: Blog Template */ ?> <?php get_header(); ?> <h1>Blog posts</h1> <div class="container"> <?php while(have_posts()): the_post(); ?> <?php the_content(); ?> <?php endwhile; ?> </div> <?php get_footer(); ?>
The template for displaying all your posts should not be a custom page template. You should set the page you want to use as your Posts page in _Settings > Reading_. Then, as per the Template Hierarchy, your theme will automatically use `home.php` for this page, or `index.php` if that does not exist. So you should save your template as `home.php`, without the `/* Template Name: Blog Template */` comment, and set the page you want to use for displaying posts in _Settings > Reading_.
stackexchange-wordpress
{ "answer_score": 1, "question_score": 0, "tags": "posts" }
sanitize POST arrays I'm trying to sanitize some arrays received through $_POST[] and insert them into database. How should I do that? The html is name="room_types[]" $room_types = $_POST['room_types']; how to sanitize this array?
You can use `array_map` like this: $room_types = isset( $_POST['room_types'] ) ? (array) $_POST['room_types'] : array(); $room_types = array_map( 'esc_attr', $room_types ); // Replace esc_attr with your desire sanitization
stackexchange-wordpress
{ "answer_score": 0, "question_score": 1, "tags": "database, array" }
Plugin updates, change file permissions on WordPress I have a strange problem with my wordpress websites. Every time I perform plugin updates, the file permissions on my server, are changed. I get the Forbidden error in my developer console for the plugins directory that I've just update . I use a local server with Webmin/Virtualmin to managed all my wordpress websites. So, I have virtual host for every website, and I have the same problem with all of the websites. After updating the plugins, I have to change the file permissions, with default permissions for the wordpress, and everything works. This are my default permissions for every wordpress website sudo find . -type d -exec chmod 775 {} \ sudo find . -type f -exec chmod 664 {} \
**PROBLEM FOUND:** So the problem was in a separate config file. The websites were migrated from another hosting and that hosting had a separate config file which was required in the `wp-config.php` . I the other config file I found this settings: define( 'FS_CHMOD_DIR', ( 0755 & ~ umask() ) ); define( 'FS_CHMOD_FILE', ( 0644 & ~ umask() ) ); I remove this 2 lines from config file, and everythig works fine !
stackexchange-wordpress
{ "answer_score": 0, "question_score": 0, "tags": "plugins, permissions" }
Wordpress editor: "pick from existing tags" is gone? In the olden days of Wordpress, I could compose a new post and pick from existing tags using the "Tags" section in the right sidebar. With the current editor, that "Tags" section still lets me enter new tags - but "pick from existing" is gone. ![enter image description here]( Short of opening the list of existing tags in a new window (`/wp-admin/edit-tags.php?taxonomy=post_tag`), how do I get this useful functionality back?
You mean this? ![]( It's been on discussion 2 years ago and I think it is one of the reasons why Gutenberg is not really beloved by many people. If you don't rely on Gutenberg and need the feature so badly, you can use a plugin that enables the Classic Editor for posts, at least. I know that is not a perfect solution, but I'm not aware of any plugin to do what you need for Gutenberg and maybe your posts are of simpler nature, so that they won't need Gutenberg at all.
stackexchange-wordpress
{ "answer_score": 1, "question_score": 1, "tags": "tags, block editor" }
Suddenly extra hex string in <script> tags By accident I saw that a hex string is added to all `<script>` tags. Example: <script src=' type="11c18651ae5f866771d68c33-text/javascript"> ^^^^^^^^^^^^^^^^^^^^^^^^^ </script> _Of course, I have done the normal procedure:_ 1. I disabled all plugins 2. I emptied the `functions.php` file. 3. I activated/switched to the default theme `Twenty Seventeen`. **\--> Nothing changed!** Each time I press F5 the hex string changes - as it would be the PHP session id. I don't want to post the URL here to avoid to be classified as a spammer. Any idea what this can be as it doesn't make any sense? This came up in the past weeks.
It was Cloudflare `Rocket Loader` option which caused this. I disabled `Rocket Loader` and it has gone. Edit: In the Cloudflare support page is this very clear note and it explains all: ![enter image description here]( So, before I validate the page I disable it in order to avoid useless warnings and then I turn it on again.
stackexchange-wordpress
{ "answer_score": 1, "question_score": 0, "tags": "javascript, tags" }
How to check if Wordpress object type is already extended by pods I'm looking to dynamically setup some pods housekeeping when a certain plugin is installed. I can easily check to see if a certain pod object has been set up (and create the pod type programatically if it hasn't) by using the following code: // Set up the Pods API object $pods_api = pods_api(); // Check to see if the post type has already been set up if ( !pods('custom_post_type_1') ) { // Create the new post type if it hasn't been set up already $new_pod_object_id = $pods_api->add_pod($params); } This works for new custom pod types, but how to I check for pods extending an object like `WP_User`?
It turns out that Pods handles this exactly as you would expect. It doesn't differentiate between completely new post types and extending post types in the Pods API. To check if the `WP_User` class is being extended by pods, the method is identical: // pods() returns false if there's no extended class for `user` if ( !pods('user') ) { // Do things if there's no extended User set up in Pods }
stackexchange-wordpress
{ "answer_score": 0, "question_score": 0, "tags": "custom post types, pods framework" }
How to execute existing WP Cron programmatically I have a plugin that creates a WP cron when activated. It runs every hour. I need to add a simple button somewhere in the dashboard for my client, that would trigger this cron. I don't want the client to do this from plugin's interface (e.g. Cron manager), which might seem too complex for him. Is there a native WP method or an easy way to run a specific scheduled cron?
When you register a scheduled event for WordPress' cron, the 3rd argument is a hook name: wp_schedule_event( time(), 'hourly', 'my_hourly_event' ); And you add a function to run on this hook with `add_action()`: add_action( 'my_hourly_event', 'do_this_hourly' ); This will cause `do_this_hourly()` to run whenever the scheduled event runs. This works because when the scheduled time occurs, your action is called like this: do_action( 'my_hourly_event' ); Which causes anything hooked to `my_hourly_event` with `add_action()` to run. So you can run the hooked function, like `do_this_hourly()`, manually at any time by just manually triggering your event with `do_action()`, as above, such as in response to a form submission or AJAX request. Alternatively, you can just run the hooked function directly: do_this_hourly();
stackexchange-wordpress
{ "answer_score": 5, "question_score": 1, "tags": "wp cron" }
Author comment count in author page hi i want to show author comment count in author page. this code can display current user comment count but i dont want current user i need any user please help me /* user commnet count */ function commentCount() { global $wpdb, $current_user; get_currentuserinfo(); $userId = $current_user->ID; $count = $wpdb->get_var(' SELECT COUNT(comment_ID) FROM ' . $wpdb->comments. ' WHERE user_id = "' . $userId . '"'); echo 'Şərh sayı ' . $count ; } <?php commentCount(); ?>
all you have to do is to add an param: /* user commnet count */ function get_comment_count( $user_ID ) { global $wpdb; $count = $wpdb->get_var( $wpdb->prepare( "SELECT COUNT(comment_ID) FROM {$wpdb->comments} WHERE user_id = %d ", $user_ID ) ); return $count; } <?php echo get_comment_count( <USER_ID> ); ?> PS. I've added some proper escaping in your query also, so this code is not vulnerable any more... ## But you can also use... WordPress already has its own way of doing it, so you don't have to reinvent the wheel... You can use: $count = get_comments( array( 'user_id' => <USER_ID>, // include only comments by this user 'count' => true // it will return only count of comments and not the comments ) ); echo $count;
stackexchange-wordpress
{ "answer_score": 1, "question_score": 0, "tags": "users, comments, author, count" }
Add form after woocommerce admin order edit I need to add a form after closing form tag in woocommerce admin order edit page. I need to do this because the action of this form points to an iframe... ex: <form action='someurl.com' target='myiframe'> <input type='hidden' value='myvalue' /> </form> <iframe id='myiframe' src='someurl.com'></iframe> I need to put anywhere in order details admin page... I researching by two days.. the only way i found is in the admin_footer, but the layout breaks. with admin_footer hook the there are two or three div.clear between the default form and my form... I'm asking this here because i think it is just a custom post type... if doesn't i'm sorry for that. I'm thinking in place this form in order list admin page!!! anyone can help me? thanks for helping!
You can use the other action which called before wp_footer. You can use action "in_admin_footer" // define the in_admin_footer callback function action_in_admin_footer() { global $pagenow, $current_page, $post; //$current_page->post_type === 'shop_order' if( $pagenow == 'post.php' && !empty( $_GET['action'] ) && $_GET['action'] == 'edit' && $post->post_type == 'shop_order' ) { // make action magic happen here... } }; // add the action add_action( 'in_admin_footer', 'action_in_admin_footer' );
stackexchange-wordpress
{ "answer_score": 1, "question_score": 0, "tags": "custom post types, plugin development" }
deactivate WPBakery Page Builder license I need to deactivate the license and reinstall it ... will it be such that my content that I wrote and those blocks that I set to be deleted and not appear again with the new license?
Not really. The change of license should not have a direct impact on the created content. The created blocks/content will still be stored on the database and will be accessible after enabling the new license. However, you should ALWAYS do a previous backup, just in case. It's better to be safe than sorry ;-)
stackexchange-wordpress
{ "answer_score": 0, "question_score": 0, "tags": "plugins" }
Noindex Posts From Certain Authors In Wordpress I'm trying to noindex posts from all authors EXCEPT 3 authors on my Wordpress site. I found the following code that I can put into the header.php file. However, this targets specific categories. <?php if (is_single() && (in_category(array(457)))) { echo '<meta name="robots" content="noindex, follow">'; } ?> How do I modify this to say something like, if is single post and is NOT an author with ID 111, 112, or 113 then insert noindex, follow. Would the following be correct?: <?php if (is_single() && !(is_author(array(111,112,113)))) { echo '<meta name="robots" content="noindex, follow">'; } ?>
From codex: is_author() is a conditional tag which _determines whether the query is for an existing author archive page._ so it does not work for your scope. Best solution, instead of using the template file _header.php_ is to write a function in _functions.php_ hooking the proper action `wp_head`: add_action('wp_head','AS_exclude_author_from_indexing'); function AS_exclude_author_from_indexing(){ $toIndex = array(111,112,113); $user_id = get_the_author_meta( 'ID' ); if( !in_array($user_id,$toIndex)){ echo "<meta name=\"robots\" content=\"noindex,follow\">".PHP_EOL; } }
stackexchange-wordpress
{ "answer_score": 1, "question_score": 0, "tags": "php, functions, author, noindex" }
wp_redirect goes to infinity loop I want to redirect WordPress pages as per location e.g domainname/ar, domainname/fr etc, but the code goes into an infinity loop. Here is the snippest: function redirect_location(){ //$UserDetailss = var_export(unserialize(file_get_contents(' $UserDetails = unserialize(file_get_contents(' $userCountry = $UserDetails['geoplugin_countryCode']; if($userCountry == 'AR'){ $url = home_url('/ar/'); } else if($userCountry == 'FR'){ $url = home_url('/fr/'); } else { $url = home_url('/in/'); } if (is_page() || is_home()) { wp_redirect($url); exit; } } add_action('template_redirect', 'redirect_location');
Us this code instead: function redirect_location(){ global $wp; $current_url = home_url( $wp->request ); $UserDetails = unserialize(file_get_contents( ' ) ); $userCountry = $UserDetails['geoplugin_countryCode']; if($userCountry == 'AR'){ $url = home_url('/ar/'); } else if($userCountry == 'FR'){ $url = home_url('/fr/'); } else { $url = home_url('/in/'); } if( ( is_page() || is_home() ) && ( strpos( $current_url, $url ) === false ) ) { wp_redirect($url); exit; } } add_action('template_redirect', 'redirect_location');
stackexchange-wordpress
{ "answer_score": 2, "question_score": 0, "tags": "page template, wp redirect" }
Do redirect 301 for wordpress page I have two domains, one server, the same files here and there. I want to redirect from one domain to another, but something does not work. What I write in .htaccess appears on both, as one server, the same files here and there. But the host does not have such a function and I need to through .htaccess RewriteCond %{HTTP_HOST} ^old.ch/$ [OR] RewriteCond %{HTTP_HOST} ^ RewriteRule (.*)$ [R=301,L] it's work 50/50 and doesnt work in the incognito
RewriteEngine On RewriteCond %{REQUEST_URI} (. _) RewriteRule ^(._ )$ < [L,R=301]
stackexchange-wordpress
{ "answer_score": 0, "question_score": 0, "tags": "redirect" }
#text at the begging of every page, before the main content block If you check my website (website) you can see the problem right away, I can't locate that #text anywhere ... I hope someone can help me with this frustrating problem I faced! Don't know what else to say hopefully this is enough. Thank you in advance ! ![enter image description here](
Since we know that the '#' was accidentally added when you were including the custom fonts from Google that's addressed, but as per the comments, here's the correct way to add these fonts so that you're not dropping them in your custom header. You want to place them in the head instead so you have to enqueue them. You'd add this to your functions.php file. The 'xx' at the end of each needs to be replaced, make that match your theme version. function lilika_fonts() { wp_enqueue_style( 'arvo-font', ' array(), 'xx' ); wp_enqueue_style( 'kaushan-font', ' array(), 'xx' ); } add_action( 'wp_enqueue_scripts', 'lilika_fonts' );
stackexchange-wordpress
{ "answer_score": 1, "question_score": 0, "tags": "html" }
Which action is triggered when a theme was modified? I want to intercept plugin changes, but no action hook listed in the Action Reference seems to do it. I tried `after_switch_theme` which is triggered only after changing from one theme to another, and `load_themes.php` which is triggered when entering the "Appearance" page with the list of currently installed plugins. Which action will be triggered after configuring a theme in customizer? Which action will be triggered when a file of a child theme is modified? Which action will be triggered when a theme was updated to a newer version?
Anytime changes are saved in the Customizer, there is a `customize_save_after` hook. For theme updates, you can use the `upgrader_process_complete` hook - you pass it various arguments including `'type' => 'theme'`. I don't think there are any WordPress-specific hooks for when files of a child theme are modified. This typically happens via FTP, rather than wp-admin, so it wouldn't have any hooks. You could possibly write something yourself to check the server's modified timestamp on all the theme files, but that might be fairly server-intensive to check frequently.
stackexchange-wordpress
{ "answer_score": 3, "question_score": 1, "tags": "plugin development, actions, child theme, theme customizer" }
How to prevent a specific users's profile photo (gravatar) from showing on the frontend to other users? Yes, I need a code to do that. Plugin is not an option, I need to use theme's functions.php file. Maybe this filter would help: `apply_filters( 'get_avatar', string $avatar, mixed $id_or_email, int $size, string $default, string $alt, array $args )` I have the user ID.
Use this hook function to replace user's avatar (which is passed in as HTML `<img ...>` tag) if user's ID or email matches your condition. You can use any other default image, or get individual replacement image for each user. function my_get_avatar($avatar, $id_or_email, $size, $default, $alt) { if ($id_or_email == "[email protected]") { $img = " $avatar = "<img src='".$img ."' alt='".$alt."' height='".$size."' width='".$size."' />"; } return $avatar; } add_filter('get_avatar', 'my_get_avatar', 10, 5);
stackexchange-wordpress
{ "answer_score": 2, "question_score": 0, "tags": "users, gravatar" }
How to Customize Wp Default Title and a prefix This code snippet shows (prefix) category Name first before the Post title (Very right). E.g * Music: %Post_title% * Video: %post_title% * Lyrics: %post_title% * News: %post_title% * Lifstyle: %Post_title%. Now the problem is, I wanted to show this on a very specific category(Music & Video) alone and not all categories... E.g on category Music & Video alone. Then any other post from any other category will not show any Prefix at all... Below is the code snippet: add_filter('wp_title', function ($title) { if (is_single()) { $categories = get_the_category(get_the_ID()); // Assuming the post has many categories will take the first $category = reset($categories); return $category->name .': '.$title; } return $title; } );
> Try this code. add_filter('wp_title', 'custom_title'); function custom_title($title) { if(is_single()) { $category = get_the_category(get_the_ID()); if(!empty($category)){ $categories = array('music','video'); if(in_array($category[0]->slug,$categories)){ return $category[0]->name.': '.$title; } } } return $title; }
stackexchange-wordpress
{ "answer_score": 1, "question_score": 0, "tags": "headers, wp title" }
Part of Menu Item Hidden on Header Menu My business site is built on WordPress and I am using the "Shifters Lite" WP theme right now. My issue is: One of my primary menu item (designed as per my web-pages) is getting hidden on the Header part. The page in concern is - Sitemap. For better understanding, you can view my site here: < As clearly visible, the last letter of the word "Sitemap" is getting hidden automatically. I tried multiple CSS codes, but none of them worked in my favor. So, thought of asking the experts here. Any help in this regards would be much appreciated. Thank you!
It's because you're skewing the parent container with CSS transforms. You can see in this screen capture of developer tools that the parent cuts off the content on the second row. ![Skewed Parent]( Try this: .menu-primary-menu-container{margin-right:10px;} You'll see that fixes it, so you just play around with those settings and get it exactly how you want it. Here's what happens when I add that rule in the developer tools: ![enter image description here](
stackexchange-wordpress
{ "answer_score": 2, "question_score": 1, "tags": "theme development, menus, sitemap" }
Set featured image as hero image on each page I want my post's featured image show as a full width hero image. I have tried to set the featured images as background images in a full-width row, but I think it is not possible. If anyone have the answer or a way to set the featured image as a hero, then please suggest.
You need to look at how your theme is rendering the hero image. Then, before it does so, add an if block which checks for a featured image. If a featured image exists, replace the hero image with it. Your code will look something like this. if ( has_post_thumbnail() ) { // render hero image using the_post_thumbnail() instead }
stackexchange-wordpress
{ "answer_score": 0, "question_score": 0, "tags": "posts, post thumbnails" }
How to add Wordpress Featured image in <a> tag ..? I am trying to add Wordpress featured image in tag. I used these 3 shortcodes. <?php echo $image_large[0]; ?> <?php echo get_the_post_thumbnail(null,'thumbnail');?> <?php echo get_the_post_thumbnail( $page->ID, 'full' ); ?> Example <a href="<?php echo get_the_post_thumbnail( $page->ID, 'full' ); ?>" >View Larger</a> But nothing working. Please help me ...
It's not working because you're trying to echo the image into the href. What you want is just the URL to go there. <?php echo get_the_post_thumbnail_url( $page->ID, 'full' )?> You can learn more about this function here in the codex.
stackexchange-wordpress
{ "answer_score": 0, "question_score": 0, "tags": "php, post thumbnails, cms" }
Fatal error...Please help me I am New to wordpress After installing and activating a plugin I got the following error ( ! ) Fatal error: Cannot declare class WP_Importer, because the name is already in use in C:\wamp2\www\wordpress\wp-admin\includes\class-wp-importer.php on line 5 Please help me, how to fix this error...
You have another plugin/theme adding the `WP_Importer` class. Did you install any recent plugin/theme that broke the website? If you did install a plugin that broke the website go in the `wp-content/plugins` folder and change/delete the folder of the plugin you installed. It will work again after that. You should also open a ticket with the plugin developer and describe the problem.
stackexchange-wordpress
{ "answer_score": 1, "question_score": 1, "tags": "fatal error" }
Rename the label on a menu location which is already defined? I have a menu location defined by a theme, I'd like to change the label from Header Menu to something else (but keeping all it's other settings as is), I can't find any suitable filters to do this within WordPress - is this possible? ![Menu location](
You are right there is no filter for this, you would have to hack the global instead, in this case `$_wp_registered_nav_menus`: add_action('after_setup_theme', 'custom_menu_location_label'); function custom_menu_location_label() { global $_wp_registered_nav_menus; $find = __('Header Menu'); $replace = __('Something Else'); foreach ($_wp_registered_nav_menus as $location => $description) { if ($find == $description) { $_wp_registered_nav_menus[$location] = $replace; } } }
stackexchange-wordpress
{ "answer_score": 1, "question_score": 0, "tags": "menus" }
How to make sidebar float right and site content left am trying to develop my own wordpress custom,am having problems trying to add a sidebar float left e.g something like Twenty Sixteen theme. please help am still learning. Thank you.
You would do something like this with your CSS. Setting a fixed height and whatnot is only for example purposes: #content { background: brown; width: 75%; height: 500px; float: left; } #sidebar { background: gray; width: 25%; height: 500px; float: left; } <div id="content"></div> <div id="sidebar"></div>
stackexchange-wordpress
{ "answer_score": 0, "question_score": 0, "tags": "sidebar, register sidebar" }
Need to edit themes HTML code I am working on a small online shop and I am using Averta Phlox theme. As I encounter they have bug in a shopping cart. The cart do not work on mobile phones, as I can work a little fix for it using simple css and html, I am able to fix this bug. But I can't find the place for HTML part in this because it use aux design and elementor plugin. Maybe someone can suggest the place how to find the necessary part of the code. It is a Phlox cart widget what creates cart function in header file. My test site is here - SHOP I would love to get some suggestion in this situation, because averta support are ignoring this issue for a 3 years. Thanks and sorry for bad English, it's not my native.
Can you search the theme source code for the CSS class that is used for the cart icon ("aux-shopping-basket" or "aux-phone-off" or "aux-action-on-click")? Then you could create a child theme and copy the original file and then edit the copied file to fix the error. What is the fix?
stackexchange-wordpress
{ "answer_score": 1, "question_score": 0, "tags": "themes, css, html" }
Gutenberg get wp registered sidebars In my template I have registered several sidebars with function `register_sidebar()`. Now I am looking for a way how to get list of all registered sidebars in Gutenberg. I was looking in documentation here: < but didn't find anything useful. Is it even possible to get such a data in Gutenberg?
This data is not passed into Gutenberg by default. You should create custom REST API endpoint and data store. This article might help with some code examples.
stackexchange-wordpress
{ "answer_score": 1, "question_score": 0, "tags": "sidebar, block editor" }
Trying to show the category of a post in the post display I'm very new to coding so please bear with me. I am trying to show the categories of which my post came from on the post excerpt. I have added a photo to demonstrate what I mean: ![enter image description here]( Here, the post "surgical sightings" shows the parent category "Education" as well as the 'sub-categories' under Education. I was wondering if there was a function that allows me to do this? Right now my post only has the title of the post, the date and an excerpt like this. Ideally I could add the categories under which the post is under as well. ![enter image description here]( I have spent an hour or so looking up php and css and have no idea how to edit these on my Wordpress site. Any help would be much appreciated thank you! Edit: Picture showing drop-down categories on menu. ![enter image description here]( Edit #2: Folder of my theme's php folder structure (Nisarg) ![enter image description here](
Use `the_category();` on your template. It also supports `$separator` parameter so you can use your desired separator. Example: `<?php the_category( ', ' ); ?>` will separte categories with commas. By the look of your theme folder structure, you should add `<?php the_category( ', ' ); ?>` on `child-theme`=>`template-parts`=>`content-excerpt.php`. Add it to line 22. If you want it only for the excerpt posts, use it on line 26.
stackexchange-wordpress
{ "answer_score": 0, "question_score": 0, "tags": "php, posts, categories" }
Does Wordpress Importer notify imported Users? I have exported an XML/WXR from one site with many posts and many users, using the Export tool. I want to migrate that to another site. I have begun using the Import tool. Because none of the users yet exist on the destination site, WordPress asks if I'd like to import them. I need to know - would this step initiate an email being sent out to those users upon import?
It does not. It simply imports them as if they've always been a user.
stackexchange-wordpress
{ "answer_score": 1, "question_score": 1, "tags": "users, import, export" }
Which escaping function should be use on register_post_type label? If I register a post type then which escaping should I use for escaping label? function book_setup_post_type() { $args = array( 'public' => true, 'label' => __( 'Books', 'textdomain' ), 'menu_icon' => 'dashicons-book', ); register_post_type( 'book', $args ); } add_action( 'init', 'book_setup_post_type' );
None. Escaping should happen late, on output. This is just registering the strings for later use, so it's too early to escape. All the places in WordPress where the post type label is used automatically, WordPress should already be escaping it. If you're outputting any of the labels yourself, you would probably use `esc_html()`: $post_type_object = get_post_type_object( 'book' ); $post_type_labels = get_post_type_labels( $post_type_object ); echo esc_html( $post_type_labels->singular_name );
stackexchange-wordpress
{ "answer_score": 1, "question_score": 0, "tags": "custom post types, translation" }
Is There A Way Of Using the_post_thumbnail() to Pull In A Specific Image From The Media Library I currently have a custom theme with some images in a separate image folder and I pull them into the frontend with the `echo get_theme_file_uri('/img/image-name.jpg')` which works as expected. I would like to be able to add images from the media library, I know I can do this with `the_post_thumbnail()`, but this obviously pulls in the post thumbnail relating to a post, whereas I've designed a page that uses 4 different images. Is there a template tag that pulls in an image out of the media library onto a page where I can use the image's ID, so you get the benefits `the_post_thumbnail()` brings in terms of sizing images etc ? Any help would be amazing.
The equivalent function for arbitrary images that aren't the post thumbnail is `wp_get_attachment_image()`. It works similarly, but you need to pass the attachment ID, and there's an `$icon` argument that doesn't really do much: echo wp_get_attachment_image( $attachment_id, 'large', false, [] );
stackexchange-wordpress
{ "answer_score": 2, "question_score": 1, "tags": "images, page template" }
How would I see which wordpress posts have a revision history without opening each one? I have about 3000 CPT records with ACF data that were updated incorrectly by WP All Import. Is there a way to see a list of posts with revision histories? I have already exported the database, but can't see any indicators that show if a single post has a revision. Edit: Is there a specific database for post revisions?
From the Revisions documentation page: > Revisions are stored in the posts table. > > Revisions are stored as children of their associated post (the same thing we do for attachments). They are given a `post_status` of `inherit`, a `post_type` of `revision`, and a `post_name` of `{parent ID}- revision(-#)` for regular revisions and `{parent ID}-autosave` for autosaves. So you should be able to search the `wp_posts` table for posts where the `post_type` is `revision`, and then grab the `post_parent` ID to find the original post. ## Update If you're looking for an SQL query, here's one I just tried that seemed to work: SELECT ID, post_title FROM wp_posts WHERE ID IN ( SELECT DISTINCT post_parent FROM wp_posts WHERE post_type='revision' ); ...assuming your posts table has the default name `wp_posts`.
stackexchange-wordpress
{ "answer_score": 0, "question_score": 0, "tags": "database, revisions" }
I would like to count number of comments after 5 days ago this is my code, and the result shows always the total number of comments instead of number of comments after 12 february 2020. I don't know why it does not working. #!/usr/bin/php <?php if ( ! defined('ABSPATH') ) { /** Set up WordPress environment */ require_once( dirname( __FILE__ ) . '/wp-load.php' ); } $args1 = array( 'status' => 'approve', 'date_query' => array( array ( 'after' => '2020-02-12 10:00:00', ), ), ); $comments = new WP_Comment_Query( $args1 ); $comms = get_comments( $comments ); $nbr = count( $comms ); echo "$nbr" ?> thank you for your help
thank you for WebElain to help me. This answer driving me to the right request. Now it's ok. It is an object indead and I use something more simple with get_comments () query with parameter count enabled. the final code is like this : #!/usr/bin/php <?php if ( ! defined('ABSPATH') ) { /** Set up WordPress environment */ require_once( dirname( __FILE__ ). '/wordpress/wp-load.php' ); } $output = shell_exec('date --date="10 day ago" "+%Y-%m-%d %T"'); echo "$output"; // WP_Comment_Query arguments $args1 = array( 'status' => 'approve', 'count' => true, 'date_query' => array( array ( 'after' => $output, ), ), ); //$comms = var_dump( $comments ); $nbr = get_comments( $args1 ); echo "$nbr\n"; ?> Thank you.
stackexchange-wordpress
{ "answer_score": 0, "question_score": 0, "tags": "comments" }
Disable Order Review Page when the id product how Disable Order Review Page when the id product is 50710 i use this code `remove_action( 'woocommerce_checkout_order_review', 'woocommerce_order_review', 10 );` but i need disable order review only in id product : 50700
function action_woocommerce_checkout_order_review() { // Product id $product_id = 50700; // Generate cart id $product_cart_id = WC()->cart->generate_cart_id( $product_id ); // Is product in cart $in_cart = WC()->cart->find_product_in_cart( $product_cart_id ); // Product found if ( $in_cart ) { remove_action( 'woocommerce_checkout_order_review', 'woocommerce_order_review', 10 ); } } add_action( 'woocommerce_checkout_order_review', 'action_woocommerce_checkout_order_review', 1, 0 );
stackexchange-wordpress
{ "answer_score": 1, "question_score": 0, "tags": "woocommerce offtopic" }
Pre_get_posts filter overwrites all search functionality So I have the out of the box wordpress 'Search' widget that I want to expand. I used the below filter to have the ability to search for my custom post types inside the widget: add_filter( 'pre_get_posts', function($query) { if ($query->is_search) { $query->set('post_type', [ 'post', 'profile' ,'recipe', 'dish' ]); } }); The problem that I discovered is that it overwrote ALL search items on the website, including the search box inside the admin panel 'Posts', where I was getting custom post type results although they didn't live there. Does anyone know how to improve the search functionality on the search widget to include custom post types without overwriting ALL search boxes throughout the site?
That's easy, `pre_get_posts` applies to all queries, not just those on the frontend. So if you don't want it to run on admin queries, test if you're in the admin and exit early! You might also want to verify that you're in the main query add_filter( 'pre_get_posts', function( \WP_Query $query) { if ( is_admin() ) { return; } if ( ! $query->is_main_query() ) { return; } Remember, `pre_get_posts` runs on all queries, regardless of where, be it admin, frontend, XMLRPC, REST API, etc. It will only run on the frontend if you tell it to only run on the frontend.
stackexchange-wordpress
{ "answer_score": 2, "question_score": 1, "tags": "custom post types, themes, filters" }
Is there a way to enforce the type of an object returned by a function that could return anything? I am initializing a class where the constructor requires a WP_Post object. The object I would like to pass comes from `get_queried_object()` which could return almost anything. I am using `is_a()` to make sure I have the right type, which "works", but my IDE does not recognize that I have constrained the type. Is there a way to make it clear to the IDE that I have done my due diligence? I don't want to get in the habit of ignoring my IDE. It has been so nice to me in the past and saved me from so many mistakes. :) $queried_object = get_queried_object(); if ( is_singular() && is_a( $queried_object, 'WP_Post' ) ) { // Initialize class that requires WP_Post object. $class = new ClassThatOnlyAcceptsPostObject( $queried_object ); // ... }
In addition to what Tom already said, using `instanceof` has worked quite well for me. (Actually never heard of `is_a()` before.) if (is_singular() && $queried_object instanceof \WP_Post) { // do something } Both PHPStan and my IDE know that after this check, `$queried_object` is an instance of the `WP_Post` class.
stackexchange-wordpress
{ "answer_score": 2, "question_score": 2, "tags": "php, ide" }
Not for profit membership site on Wordpress I am looking to implement a not-profit membership site where I need a following: * Only registered users can view content * If they try to view any content they need to login first with their own personal username and password. * When they logged in they can view all the posts. * Each post is going to have a pdf and when they click their link a request would be generated and it should be approved by a site admin first. Then they would get a link in an email. I found some membership plugins but they are all expensive and I do not need all their feature like payment processors. I am wondering if it is possible to implement this site in Wordpress only?
When you publish a post or page on Wordpress you can set the status to **Private**. This means that this content is only viewable to registered and logged in users. You can then restrict files to the person who uploaded them (or disable upload for non-admin). Here is an example of how to do that. You could add a PDF to each post using the Media Library and then add a link to each post that sends an email to an administrator to approve sending the PDF. With a little thought anything is possible. The following code will force post status to private: // Update Post Status to Private function force_type_private($post) { if ($post['post_status'] != 'trash' && $post['post_status'] != "draft" && $post['post_status'] != "auto-draft") { $post['post_status'] = 'private'; } return $post; } add_filter('wp_insert_post_data', 'force_type_private');
stackexchange-wordpress
{ "answer_score": 1, "question_score": -1, "tags": "membership" }
How to save order item custom attributes save into custom table how to save order item custom attributes into custom table in Woo-commerce after order placed successfully.
You can use '`woocommerce_checkout_order_processed`' action or '`woocommerce_thankyou`' hook. '`woocommerce_checkout_order_processed`' is called when order is being processed, whereas '`woocommerce_thankyou`' is called when the order is being placed.
stackexchange-wordpress
{ "answer_score": 0, "question_score": 0, "tags": "woocommerce offtopic" }
My Sites link in multisite is incorrect Within the network admin, the **My Sites** link, is not linking to the main parent site. Instead, it links to a child site blog. How can I change this link? Is there a way to rebuild WP menu? I haven't a clue how it became the wrong link. ![enter image description here](
I fixed this by deactivating then reactivating the child site under Network Admin > Sites.
stackexchange-wordpress
{ "answer_score": 0, "question_score": 0, "tags": "multisite, admin menu, network admin" }
ACF relationship fields 'The results could not be loaded' Would anyone know why the ACF relationship field is not showing results in the backend. This affects any type of relationship field - the entry list pane is just empty?
Turns out it was comments in functions.php. Probably school boy error, but if anyone can explain, would be interested to hear.
stackexchange-wordpress
{ "answer_score": 0, "question_score": 0, "tags": "advanced custom fields" }
How to parse a shortcode within a shortcode? I've created a quick function and shortcode to allow me to include logged-in user only content: function content_for_logged_in($atts,$content){ $logged_in_content = ""; if(is_user_logged_in()){ $logged_in_content = $content; } return $logged_in_content; } add_shortcode('logged-in-content','content_for_logged_in'); But it doesn't parse shortcodes that are within the content, e.g.: [logged-in-content] <p>Some test content...</p> [wpforms id="752"] [/logged-in-content] ...in this case, the wpforms shortcode is displayed rather than the form. Is there a way to alter my function so that shortcodes within the content will be parsed? Thanks, Scott
The function you are looking for is named `do_shortcode` (there will also be a function `apply_shortcode` in Wordpress 5.4 that does the same). Codex Page For your example, this will work: function content_for_logged_in($atts,$content){ $logged_in_content = ""; if(is_user_logged_in()){ $logged_in_content = do_shortcode($content); } return $logged_in_content; } add_shortcode('logged-in-content','content_for_logged_in'); Happy Coding!
stackexchange-wordpress
{ "answer_score": 1, "question_score": 0, "tags": "functions, shortcode" }
Wordpress cutting images size I'm currently working on a page's banner , and after a while i've noticed that my images are with slight worst quality that i expected. I was uploading the images with the 1920x1024 size, but after i checked admin dashboard i noticed they have been shrunk to 1024x575 ! Is there any reason why this happens ? And is there anyway to prevent this ? Thanks in advance!
Maybe the method you're using to display the banner is using a specific image size. Usually wordpress can use a defined (or not) image size to display a media item, but if you check the media item, you'll be able to see the original upload. Can you provide some code where you're displaying the banner? You should check out the add_image_size, get_the_post_thumbnail methods and also if you should change the method to display the image.
stackexchange-wordpress
{ "answer_score": 1, "question_score": 0, "tags": "images" }
Remove the month and year from a WordPress Date? So, I am wondering if there is a way that I can make this: February 28th, 2020 Just output NO month and NO year so just 28th (i.e. just the date) What approach would you take? I am applying this to a WordPress plugin called Pods. The plugin allows for Custom Fields to be printed like this: {@date} And I know that you can run a PHP command from the functions file like this: {@date,remove_month} But figuring how to do that is tricky...any pointers?
You’ll need to write your OWN function that will take the post_date and return it reformatted to the style you’re looking for. function my_date($input_date) { return date("S", strtotime($input_date)); } And then you would call it within your Pods Template like {@post_date, my_date} All rights goes to Jim True. More infomations : <
stackexchange-wordpress
{ "answer_score": 1, "question_score": 0, "tags": "functions, date" }
Gutenberg dependencies in package.json Seeing as `@wordpress/scripts` will magic my development versions of `@wordpress/*` dependencies, should any of them be present in the `package.json` for my own block development? Gutenberg examples package.json refers exclusively to `@wordpress/scripts` despite the entrypoint file referring to `@wordpress/i18n` and `@wordpress/blocks`. Should I do the same?
Yes and no, it depends... The WP Scripts package depends on the `@wordpress/dependency-extraction-webpack-plugin` package at: < What this will do is search for packages from `@wordpress` and list them in a file to make it easy for you to load the list of dependencies when enqueuing. It also adjusts webpack so that it knows not to compile in those dependencies, but instead rely on WordPress to provide them at runtime via enqueuing. As a result, the packages aren't needed, and you don't end up with 20 copies of `@wordpress/element` loaded on the page from every extra block installed. So, you don't need to put `@wordpress/element` in your `package.json` requirements when using wp scripts to build the assets. This only applies to WordPress packages though. Other libraries on the other hand get included the normal way.
stackexchange-wordpress
{ "answer_score": 1, "question_score": 0, "tags": "javascript, block editor" }
What is the Wordpress approach to custom data? I'm new to Wordpress development. I want to create a stock portfolio management section on my site. In the admin panel I want to create a portfolio, enter stocks, what price they're purchased at, and track the latest price of those stocks, generating portfolio return statistics and so forth. But I'm not sure the Wordpress-acceptable way of doing this. I know how to create settings forms and so on, but this doesn't seem to fit into that approach.
Welcome! As the comment from jdm2112 says, WordPress has the ability for you to create Custom Post Types. You can also make custom taxonomies, custom fields, and more. If you're new to this, then I would recommend you check out Generate WP as a resource. I find it's a great tool for getting a handle on what's possible. **Make your CPT** There are many plugins that can help you do this, but it is very easy to create your own. If you need to get an idea of what that looks like, head over to the WP post type generator and play around with it for a bit. Once you feel like you've got a handle on it, you can add it to your theme functions.php, or even better, make your own plugin (my personal recommendation). **Add Custom Fields** You can make your own meta boxes as well, but I actually recommend ACF for this. Their pricing for Pro has gone up considerably, but their product is pretty dang amazing. I hope that helps get you started. CPT and ACF are my WP bread and butter.
stackexchange-wordpress
{ "answer_score": 1, "question_score": 0, "tags": "plugins, plugin development, database" }
Can the Gutenberg editor be toggled closed? You know how you have control over what page options show when editing pages and posts? You can open and close them with the little triangle toggle - and you can rearrange them, so if you wanted the Yoast bar to sit above the Comments bar, you could just move it there. IS there any way to do this with Gutenberg? I have like 8 Advanced Custom Fields I need to show ABOVE the Gutenberg edit part of the page.
You can't move metaboxes/panels above the content area, they don't logically sit in the same place/depth. Unlike the classic editor where everything is listed vertically by HTML markup, that's not how the block editors UI was designed. Instead there's a canvas with a block-list component, and a frame that contains the top toolbar, the sidebar, and optionally a drawer/area for metaboxes. If you want to place controls and options above the content, they will need to be built as blocks. Otherwise what you want doesn't fit into the new paradigm. Perhaps your post type has a template defined on register that locks it to a custom block you built, and allows child blocks that make up your content? Or perhaps you can make use of ACF blocks
stackexchange-wordpress
{ "answer_score": 0, "question_score": 0, "tags": "block editor" }
How to manage arrays from custom functions stored in functions.php? In functions.php I have made the following code: add_action( 'listofnames', 'SomeNames' ); function SomeNames(){ $names=array( "john","edgar","miles"); return $names; } It should return array I wish to manipulate with, but when in index.php I try, it goes wrong. Obviously it does not work this way: do_action('listofnames'); foreach (do_action('listofnames') as $n){ echo $n; } Can anybody help me to manage this?
A callback for an action doesn't return anything, because that return value is never passed through by WordPress. Use a filter instead: add_filter( 'listofnames', 'SomeNames' ); function SomeNames() { $names=array( "john","edgar","miles"); return $names; } And in your template you call it like this: $names = apply_filters( 'listofnames', [] ); foreach ( $names a $name ) { echo $name; }
stackexchange-wordpress
{ "answer_score": 2, "question_score": 1, "tags": "functions, actions, array" }
How to show the hero of website when sending website link? when someone send a link of a website in facebook, sometimes it shows the hero image of the website.Like this:![image 1]( How can i set that for my website?
This image is fetched from the OG:IMAGE tag from Open Graph protocol. You may define an image by displaying this tag in your page : <meta property="og:image" content=" /> Note that you need to define the image URL in the _content_ attribute. You may use a plugin like Yoast SEO to define it in any page or post.
stackexchange-wordpress
{ "answer_score": 0, "question_score": 0, "tags": "customization" }
How to use the CSS of the Wordpress core in the development of my administration page? I am currently creating the administration window for my wordpress plugin, my objective is to create this screen using the same CSS that are already used within the different tabs of the "wordpress administrator". **My question is if there is any link (or list of links) where all the CSS classes used by the Wordpress core are defined to render the "Wordpress administrator"** (something like Bootstrap has in its documentation link) At the moment I was able to perform some experiments using the information in this link as well as analyzing with my browser the classes that have applied some parts of the HTML code ![enter image description here]( If there is not what I consult in my first question, t **he only thing I would have left to use these CSS styles would be to analyze the part that interests me with the browser and see the classes they have applied to then put them in my code?**
Frank Bültge has a plugin which displays all (most?) of the WP admin styles, which is kept fairly up-to-date: < Helen Hou-Sandí also has a plugin style guide: < There is also this: <
stackexchange-wordpress
{ "answer_score": 1, "question_score": 0, "tags": "plugins, plugin development, theme development, admin" }
Applying metatag to single page I want to change the viewport metatag for a single page on my website. I want the rest of the website to adhere to the following: <meta name="viewport" content="width=device-width, initial-scale=1"> But I want one particular page (id=7730) to adhere to this: <meta name="viewport" content="width=device-width, initial-scale=0"> Any help is greatly appreciated - I'm a backend/html/php beginner, so layman's terms are helpful!
You can use the WordPress conditional tags to accomplish this. Both `is_page()` and `is_singular()` should work, you just need to pass a slug, or in your case, an ID. Then we can use the `wp_head` hook to conditional add in the meta tag. You can add the following function and hook into your `functions.php` file. /** * Conditionally add metatag to specific page * * @return void */ function wpse359922_metatag_conditional() { if( is_page( 7730 ) ) { echo '<meta name="viewport" content="width=device-width, initial-scale=0">'; } else { echo '<meta name="viewport" content="width=device-width, initial-scale=1">'; } } add_action( 'wp_head', 'wpse359922_metatag_conditional' ); On a side-note, your whole website _should_ be mobile friendly otherwise it will get dinged on SEO by engines like Google and Bing.
stackexchange-wordpress
{ "answer_score": 0, "question_score": 0, "tags": "html, mobile" }
How can I get the url from file uploaded in Media Library In my template i'm using a link for downloading a file (probably a PDF or a JPEG) that I will upload from Media Library. How can I get the url path for this specific file? What template tag I have to use? Thanks
I think that the best way is to upload the file in a separate folder from media library and then call it by using get_stylesheet_directory_uri(); For example: dist/img/cv.pdf">
stackexchange-wordpress
{ "answer_score": 0, "question_score": 0, "tags": "links" }
How to show contact form popup in same page I'm designing my WordPress Website. I don't want my visitors to go for new page on clicking the contact us/get in touch button. I want my form to show up as popup (only when clicked on button).
if you are using Contact Form 7 which is usually one of the popular free plugins you can use shortcode to display forms on a normal page by copying this into the editor and editing the form ID and title as needed. [contact-form-7 id="1234" title="Contact form 1"] EDIT: You can use simply jQuery to hide/show the form <
stackexchange-wordpress
{ "answer_score": 0, "question_score": 0, "tags": "php" }
How we can reduce wordpress page loading time? How we can reduce wordpress page loading time ?
**LiteSpeed Cache** (1,033total ratings) All-in-one unbeatable acceleration & PageSpeed improvement: caching, image/CSS/JS optimization… < **Autoptimize** (994total ratings) Autoptimize speeds up your website by optimizing JS, CSS, images (incl. lazy-load), HTML and Google Fonts, asyncing JS, removing emoji cruft and more. < **other plugins:** <
stackexchange-wordpress
{ "answer_score": -1, "question_score": 0, "tags": "performance" }
How to remove private posts from RSS feeds? Private posts are visible only to administrators and editors, but I have found that they are displayed publicly in RSS feeds. How can I remove them from there? I have this code but it doesn't work: function removeRssPrivatePost($content) { global $post; if ($post->post_status == 'private') { return; } return $content; } add_filter('the_excerpt_rss', 'removeRssPrivatePost'); add_filter('the_content_feed', 'removeRssPrivatePost');
The same way you would change which posts WP shows on any other screen, `pre_get_posts`! If you ever see WP pull in posts, and want to modify what it fetches from the DB, use the `pre_get_posts` filter E.g. something similar to this: add_action( 'pre_get_posts', function( \WP_Query $query ) { if ( !$query->is_feed() ) { return; // this isn't a feed, abort! } $query->set( 'post_status', 'publish' ); // we only want published posts, no drafts or private } );
stackexchange-wordpress
{ "answer_score": 0, "question_score": 0, "tags": "rss, feed, private" }
Hi everyone, I have Problem with using wp_die() I have created a custom registration form in WordPress and everything works fine. The error handling and database operations also fine. The only problem is that the JSON response I return is printed on all pages in WordPress including admin account, dashboard, pages, and all posts. I have looked for in it google, the only thing I got is to use wp_die() if I use this wp_die() at end of my functions.php files function I get a white page without issue resolved. Can anyone know any solution for this? I have attached the screenshot of the WordPress dashboard.![enter image description here](
I used Class to embed functions in function.php file. And also used namespace to call ajax requests. So no conflicts in displaying messages
stackexchange-wordpress
{ "answer_score": 0, "question_score": 0, "tags": "wp admin, json" }
Will the same Wordpress logins work after a site migration? I am about to migrate my site to a new host, after the site and database is migrated over, will I be able to login to the back end with the same username & password?
Yes. User login data is stored in the DB which will not change in your example.
stackexchange-wordpress
{ "answer_score": 0, "question_score": 0, "tags": "login, migration" }
Where to put code that customizes API I am building a native mobile app where I need to display categories of products in different screens, and my client uses Wordpress as their CMS. I see that in order to return images from a gallery, I will need to use get_post_galleries() or get_post_gallery() per the instructions here: How to get the attached gallery in the rest API? My question is, to which file do I add the custom endpoints? So far my CMS is very bare bones so for the purposes of this question, you can assume I only have the files included with a new Wordpress installation.
Typically changes like this you would either create a plugin or create a child theme and put your code in your child theme's functions.php file. You make changes to a child theme because if your theme updates you will lose any changes you have made directly to it. Code in a plugin is always run as long as the plugin is active, where as code in a theme or child theme won't work if you change themes down the road. If the changes you want to make are not theme specific its probably best to just create a small plugin. Which is really nothing more than adding a comment at the top of a PHP file. Here is an example plugin... <?php /* Plugin Name: Example Plugin */ // Your PHP here Name this file, something like example-plugin.php, put it in the plugin directory then activate it in the admin. Here is some info on creating a child theme. Good article on plugins vs themes.
stackexchange-wordpress
{ "answer_score": 0, "question_score": 0, "tags": "images, mobile, cms" }
How to display posts i grid photo am trying to make grid view of posts for a specific category any one to help <?php $args = array( 'post_type' => 'post', 'category_name' => 'featured', 'posts_per_page' => 5, 'post__not_in' => get_option( 'sticky_posts' ) ); $the_query = new WP_Query( $args );?>
You need to build the query and then loop through it afterwards. <ul> <?php //Your Args $args = array( 'post_type' => 'post', 'category_name' => 'featured', 'posts_per_page' => 5, 'post__not_in' => get_option( 'sticky_posts' ) ); // The Query $query = new WP_Query( $args ); // The Loop while ( $query->have_posts() ) { $query->the_post(); echo '<li>' . get_the_title() . '</li>'; } ?> </ul> Then where the code echos the title, you would include your HTML to build your grid. And obviously have extra CSS elsewhere to style it as a grid.
stackexchange-wordpress
{ "answer_score": 0, "question_score": 0, "tags": "design" }
is it possible to create a website with wordpress with these requirements without coading? is it possible to create a website with wordpress with these requirements without coading? if possible which would be the best theme?Thank you. Website Requirements 1.Need to be an eCommerce marketplace 2.Need to accept paypal, credit card payments etc. 3.Manage inventory and products 4.Be able to cross sell on eBay, Amazon, Facebook, Instagram 5.Show shipping estimates to local and overseas customers. 6.Should be able to easily manage products from suppliers, thus staying upto date with supplier stock on hand. 7.Be able to run promotions and sales on products.
Apart from cross selling, all requirements are covered by a standard installation of WordPress with the WooCommerce plugin. I've seen (but never used) a free extension for Facebook. For the other platforms you need to search for extensions, maybe payed extensions on woocommerce store or codecanyon. I can not tell you what would be the best theme, but maybe the Hello Theme by Elementor and the Plugin Elementor is a good fit to customize everythin without coding.
stackexchange-wordpress
{ "answer_score": 0, "question_score": -1, "tags": "themes" }
Replace <p>-tag in the_excerpt I want to replace the -tag around the_excerpt. Right now html-output looks like this: `<p> ...content of the excerpt... </p>` I want to achieve this: `<h2> ...content of the excerpt... </h2>` I tried to use the following code in the `content-page.php` but it does not change anything. <?php the_excerpt( '<h2>', '</h2>' ); ?> Do you have any suggestions?
You should try this: function replace_tag($string){ $search = array('<p>', '</p>'); $replace = array('<h2>', '</h2>'); echo str_replace($search, $replace, $string); return $string; } add_filter('the_excerpt', 'replace_tag'); or this: function replace_tag($string){ $replace = array( '<p>' => '<h2>', '</p>' => '</h2>' ); $string = str_replace(array_keys($replace), $replace, $string); return $string; } add_filter('the_excerpt', 'replace_tag');
stackexchange-wordpress
{ "answer_score": 0, "question_score": 0, "tags": "tags, html, excerpt" }
Serialized settings in rest api I have registered settings and need it to be showed in REST API. $args = [ 'show_in_rest' => true ]; register_setting('default_sidebars', 'default_sidebars', $args); When I save a single value and then request data on endpoint `/wp-json/wp/v2/settings`, everything works perfectly. But the problem is that I save serialized data like this. a:2:{s:4:"post";s:7:"general";s:4:"blog";s:9:"sidebar_1";} Now I would expect in response something like this: default_sidebars: { post: "general", blog: "sidebar_1" } But instead I got `default_sidebars: null`. What should I do to get my data in REST API?
## JSON Schema It's supported if you explicitly register the **object JSON schema** as: $args = array( 'show_in_rest' => array( 'schema' => array( 'type' => 'object', 'properties' => array( 'post' => array( 'type' => 'string', ), 'blog' => array( 'type' => 'string', ), ) ), ), ); register_setting( 'default_sidebars', 'default_sidebars', $args ); Resulting in the following object: default_sidebars: { post: "general", blog: "sidebar_1" } in `/wp-json/wp/v2/settings` for the serialized option data: a:2:{s:4:"post";s:7:"general";s:4:"blog";s:9:"sidebar_1";} See similar object schema support for `register_meta()` in 5.3: <
stackexchange-wordpress
{ "answer_score": 5, "question_score": 2, "tags": "options, rest api, settings api" }
Parse error: syntax error, unexpected ',' I have been following along a basic tutorial on creating a simple theme structure. I have searched quite a few articles to get an understanding and looked at debugging tips, however I am at a loss, probably due to me limited knowledge base. At this stage I had downloaded bootstrap css and js folders. This is on a local server and I don't have any plugins installed or activated. After quite a number of error messages I have come down to this one. Sorry, I don't remember what changes I made in the functions file to get to this one. Parse error: syntax error, unexpected ',' in D:\xampp\htdocs\myih\wp-content\themes\mytheme\functions.php on line 8 (line 8 starts at wp_register.....) ![enter image description here]( Thanks
You've got unbalanced and improperly placed closing parenthesis. There shouldn't be the closing parenthesis after the `'stylesheet'`. Because the closing parenthesis is there, the PHP processor thought that was the end of the function's parameters. Which caused the comma character after that to cause the error. Watch the balancing of your parenthesis (and quotes) as you are writing your code.
stackexchange-wordpress
{ "answer_score": 1, "question_score": 0, "tags": "php" }
Update post meta dynamically I am trying to insert/update post meta when the user registers. Before writing that action, I am testing this code on the page so whenever the page refresh it will insert/update the post meta. > **Question:** However, the below code is not inserting/updating anything in post meta. Can anyone tell me what is wrong in this code or how to fix it? $groupItem = get_post(123); if ($groupItem && $groupItem->post_type == 'cpt_group') { $meta = 'group_users'; $user_ids = get_post_meta($groupItem->ID, $meta, TRUE); if ( ! $user_ids) { $user_ids = []; add_post_meta($groupItem->ID, $meta, array_push($user_ids, 26)); } else { update_post_meta($groupItem->ID, $meta, array_push($user_ids, 26), $user_ids); } }
Basically, you're not properly using `array_push()`. `array_push()` modifies the original/input array which is passed by reference to the function and it returns the new number of elements in the array. So with `add_post_meta( $groupItem->ID, $meta, array_push( $user_ids, 26 ) )`, you're actually setting the meta value to the number of items in `$user_ids` and not the items in the array -- so for example, `add_post_meta()` would get a `1` instead of a `[26]`. So if you want to use `array_push()`, you could do it like so: if ( ! $user_ids ) { $user_ids = []; array_push( $user_ids, 26 ); add_post_meta( $groupItem->ID, $meta, $user_ids ); } else { $prev_user_ids = $user_ids; // backup old values array_push( $user_ids, 26 ); update_post_meta( $groupItem->ID, $meta, $user_ids, $prev_user_ids ); } Or simply use `$user_ids[] = 26;` ..
stackexchange-wordpress
{ "answer_score": 1, "question_score": 0, "tags": "post meta" }
Running a function on post update with new post meta I am trying to run a function on post update by checking if an ACF is equal to something. I'm checking if the ACF value is equal to new or closed. when i change it from value new to closed and save it doesn't run but if i save the post again when the post is at closed it does run. function check_values($post_ID){ if(get_field('status', $post_ID ) == "closed") { sendSMS(); } } add_action( 'post_updated', 'check_values', 10, 3 ); //don't forget the last argument to allow all three arguments of the function Is there something I'm missing about this? I want to avoid saving each post twice. Thank you
Please try using `acf/save_post` action that will hook in after ACF data has been saved. add_action('acf/save_post', 'check_values'); function check_values($post_id){ if(get_field('status', $post_id ) == "closed") { sendSMS(); } }
stackexchange-wordpress
{ "answer_score": 1, "question_score": 0, "tags": "theme development, post meta, advanced custom fields" }
Display post of specific category on page What's wrong in the code below ? Even after comparing it with pre-existing codes, I don't get the mistake: $args = array('cat' => 367); $arr_posts = new WP_Query($args); if ($arr_posts->have_posts()) { while ($arr_posts->have_posts()) { $arr_posts->the_post(); } } else { echo "No posts found"; } Result: Nothing appears, not even the "No posts found" message. But the page is displayed without any error message.
There's nothing in your code that outputs anything for each post. That's not what `$arr_posts->the_post();` does. You need to use template tags like `the_title()` and `the_content()` to output those fields: while ($arr_posts->have_posts()) { $arr_posts->the_post(); the_title( '<h2>', '</h2>' ); the_content(); }
stackexchange-wordpress
{ "answer_score": 1, "question_score": -1, "tags": "php, posts, categories" }
How do I avoid color distortion of uploaded images? When uploading image files to the Wordpress media library the colors are occasionally distorted. This is especially noticeable in the blue tones. I think it is due to a missing conversion of the color space. Does anyone know what is the solution?
You must use standard color profiles, and convert your color profile to sRGB (in Photoshop -> Save for the web -> convert to sRGB checkbox). You should also set quality compression to 100 add_filter('jpeg_quality', function($arg){return 100;});
stackexchange-wordpress
{ "answer_score": 0, "question_score": 0, "tags": "images" }
How to automatically redirect to custom admin menu after plugin activation? I need a function to redirect user to the plugin settings page, right after plugin activation. I use this function to create a custom menu settings page: // add option page menu link function axl_ads_add_admin_menu() { $icon = 'dashicons-align-left"'; add_menu_page( 'AXL Ads', 'AXL Ads', 'manage_options', 'axl_ads', array($this, 'axl_ads_options_page'), $icon, '3' ); } And my settings page url is: `wp-admin/admin.php?page=axl_ads` Any help with this, please?
You can use register_activation_hook(). Add this to your plugin, tested and works. register_activation_hook(__FILE__, 'redirect_after_activation'); function redirect_after_activation() { add_option('redirect_after_activation_option', true); } add_action('admin_init', 'activation_redirect'); function activation_redirect() { if (get_option('redirect_after_activation_option', false)) { delete_option('redirect_after_activation_option'); exit(wp_redirect(admin_url( 'wp-admin/admin.php?page=axl_ads' ))); } }
stackexchange-wordpress
{ "answer_score": 1, "question_score": 0, "tags": "plugins, plugin options" }
add_theme_support('post-thumbnail') not working I am new to Wordpress and following a training course. Its told me to enable to use of Featured Images I need to add the following line into my functions.php: add_theme_support('post-thumbnails'); and then the following in my post types file: 'supports' => array('title', 'editor', 'thumbnail'), However I have done this but no luck getting the option to add a featured image. I have checked screen options and it is not appearing as an option I can enable. I've checked similar threads already but no luck :(
That one line is all you need, try adding this to your functions.php file. function my_theme_setup(){ add_theme_support('post-thumbnails'); } add_action('after_setup_theme', 'my_theme_setup'); I'm not sure what your "post types file" is but the above should be enough to add support.
stackexchange-wordpress
{ "answer_score": 1, "question_score": 1, "tags": "add theme support" }
Which file handles the block latest posts, I want to examine excerpt handling I'm using the latest version of wordpress and theme twentytwenty. When using the latest post block in the block editor, I am showing excerpts. It appears that using [more] to handle the length of automatic excerpts is not working properly. I tried fiddling with the max number of words setting.. I expect to be able to set the max words to, say 25, and in some post "B" put the [more] marker in at word 20, that I would get an excerpt of 25 words in post A, and 20 in post B. That doesn't work, so I try setting max words to 100, still not respecting the [more] marker. I'm a pretty good hacker, Where do I start? Is this a known problem and harder than I might expect? Thanks!
Gutenberg blocks are not stored in the Wordpress files in a readable or debuggable format. Instead, they have their own separate git repos. Here is the source for the Latest Posts Block: <
stackexchange-wordpress
{ "answer_score": 1, "question_score": 1, "tags": "theme development, block editor" }