INSTRUCTION
stringlengths
11
999
RESPONSE
stringlengths
0
999
SOURCE
stringlengths
16
38
METADATA
dict
Enqueue Style Function Not Loading I've been reading Wordpress Theme Developer Handbook to learn how things work and try to practice according to what's written in there. I've created my index.php, style.css, function.php and header and footer files. According to the Including CSS & JavaScript Part . it says that other than directly use the link tag, i need to create a functions.php and in to that file i need to add `wp_enqueue_style( 'style', get_stylesheet_uri() );` function with these parameters. I am adding this line of code to my functions.php but I can't see the file when I look at the source of the page. I also tried to add this function to my header.php instead of functions.php , it doesn't seem to work.
Your call to `wp_enqueue_style()` looks good and `functions.php` is the right place, but your code should be wrapped inside a function attached to the `wp_enqueue_scripts` hook. See the Combining Enqueue Functions section of the page you referenced for a full example. Generally speaking, any code you run in WordPress should be run on some hook or filter. Otherwise the code will be run as soon as the code is read which is usually not the correct time. function mytheme_add_theme_scripts() { wp_enqueue_style( 'style', get_stylesheet_uri() ); } add_action( 'wp_enqueue_scripts', 'mytheme_add_theme_scripts' );
stackexchange-wordpress
{ "answer_score": 0, "question_score": 1, "tags": "css" }
Dropdown contents hidden behind content I know this question has been asked across the net plenty of times already, but despite that, I still can't seem to figure out a feasible solution! :( I'm sure it's a simple fix... As the title implies, I'm struggling to get some dropdown boxes to show its contents above everything else. I've tried z-index, which perhaps seems like the obvious solution... but perhaps I'm putting the code in the wrong place? * Here's a video of the issue: Link 1 * Here's a link to the issue: Link 2 Your input and time is much appreciated! :) As a bonus, if you can also figure out how to inline the left and right elements like this, good karma will be sent your way <3 Thanks, \- D
This selector #buddypress div.item-list-tabs ul li is set to overflow: hidden; Remove that rule or change it to `visible` to show the drop-down menu.
stackexchange-wordpress
{ "answer_score": 0, "question_score": 0, "tags": "css" }
WordPress Errors? Update Failed! data.min.js So I am getting this weird error anytime I try to edit or save a new page/post. I activated a default theme and disabled the only 2 plugins I had activated but I am still getting the error. I don't even know where to begin to troubleshoot this. ![enter image description here](
This ended up being an error I had in the .htaccess file. I replaced that with a default WP one and everything is good!
stackexchange-wordpress
{ "answer_score": 1, "question_score": 3, "tags": "javascript, errors, 500 internal error" }
Can I move a Wordpress installation to an IP (without domain name)? I have a Wordpress installation in a subfolder of a domain: < I want to move it to a hosting space with no domain name: < Will it work? I want to try Duplicator or maybe manually, but I don't know if it will work without a domain name? Thanks.
Yes, it will work as far as I know. You need to make sure that you have the two URL constants pointing to the right folder on your webspace. See in your database XX_options table: siteurl: 123.123.123.123/wordpress home: 123.123.123.123/wordpress These fields can be edited via Settings > General below the 2 fields of title and subtitle, so there is no need to fool around in the database.
stackexchange-wordpress
{ "answer_score": 1, "question_score": 0, "tags": "installation, ip" }
Hide BBPress create topic on one page Hi sorry this is really basic question. I was just starting to explore wordpress and bbpress, I have a page with the forum index using the shortcode, when I enter a forum it has all the topics and the create topic form. I would like to hide this on this page only. The css to do for the whole document is as follows: `fieldset.bbp-form { display: none; }`. This is good but I would like the form to display on other pages. I have already `.page-id-143 * fieldset.bbp-form { display: none; }`. I appreciate this won't work because it is in some equivalent of an iframe. If there is an answer then I have never really used PHP before so could it be in very simple person terms. Thanks in advance.
This took as surprisingly long time but I managed to figure it out: fieldset.bbp-form { display: none; } .page-id-170 * fieldset.bbp-form { display: block !important; } I know this hides all and only shows on page id 170, and this is the opposite of what I asked but it suits my needs. An answer more accurate to the question would be: fieldset.bbp-form { display: block; } .page-id-170 * fieldset.bbp-form { display: none !important; } For both examples you would replace `.page-id-170` with `.page-id-(your page id)`. A quick guide to finding the page id: <
stackexchange-wordpress
{ "answer_score": 0, "question_score": 0, "tags": "css, child pages, bbpress" }
Filter Gutenberg Blocks Content I have a simple terms page made up of heading and paragraph blocks. I'd like to filter the_content before output in order to get the content of any heading blocks and create a menu with links to named anchors at the top. Of course, by the time I filter `the_content` passing `$content` it's already just a string of HTML, no block info. How might I fetch an array of all the 'blocked' content in my the_content filter? Or is there a better way to achieve this that I'm missing? EDIT Or perhaps I should be running a filter on save rather than at output..?
Have you tried using `parse_blocks()` (pass in `get_the_content()`)? That returns an array of all the blocks in your content. From there you can pull out block names and id attributes using an array map or foreach. Assuming you only want to pull anchor tags from the headings, you could do something like: $blocks = parse_blocks( get_the_content() ); $block_ids = array(); function get_block_id( $block ) { if ( $block['blockName'] !== 'core/heading' ) return; $block_html = $block['innerHTML']; $id_start = strpos( $block_html, 'id="' ) + 4; if ( $id_start === false ) return; $id_end = strpos( $block_html, '"', $id_start ); $block_id = substr( $block_html, $id_start, $id_end - $id_start ); return $block_id; } foreach( $blocks as $block ) { $block_id = get_block_id( $block ); if ( $block_id ) array_push ( $block_ids, $block_id ); }
stackexchange-wordpress
{ "answer_score": 2, "question_score": 2, "tags": "filters, the content, block editor" }
Make WooCommerce product categories only show images on homepage I am trying to set up my site so that my WooCommerce product categories only show images on my home page. Currently I have this: <?php function fp_categories() { if( is_front_page() ) { add_action( 'woocommerce_before_subcategory_title', 'woocommerce_subcategory_thumbnail', 10 ) ; } else { remove_action( 'woocommerce_before_subcategory_title', 'woocommerce_subcategory_thumbnail', 10 ) ; } } ?> This does remove the images, but it does so from every page. I've tried using `is_home` instead of `is_front_page`, but it didn't help either. Any suggestions?
Try running your function hooked into the template_redirect action like so: <?php function fp_categories() { if( is_front_page() ) { add_action( 'woocommerce_before_subcategory_title', 'woocommerce_subcategory_thumbnail', 10 ) ; } else { remove_action( 'woocommerce_before_subcategory_title', 'woocommerce_subcategory_thumbnail', 10 ) ; } } add_action( 'template_redirect', 'fp_categories' ); ?> I'm fuzzy on the logic why this works - I believe otherwise the functions are running before they're available, but hopefully, someone can further clarify.
stackexchange-wordpress
{ "answer_score": 0, "question_score": 0, "tags": "php, woocommerce offtopic, frontpage" }
When a plugin gets updated from the repo, does the "activation" hook fire again? When you activate a plugin, it goes through the whole activate .. bounce to the next page thing. Does the plugin fire that hook when it is updated, or only during the initial installation?
The activation hook is only fired when the plugin is first activated, not when it's updated.
stackexchange-wordpress
{ "answer_score": 3, "question_score": 1, "tags": "hooks, activation, plugin repository" }
I can not include page to wordpress function add_filter, the_content **Wordpress Function add_filter** I want to include extra page, on add_filter How can I correct this ? Thanks in Advance ! function page_content($content) { global $post; if ( is_object( $post ) && $post->ID == 134 ) { if(is_page()) { $extra_content = ' This is my extra content'; $content .= $extra_content; $content .= include('horo-header.php'); } return $content; } } add_filter('the_content', 'page_content');
I think the problem is that the PHP `include()` function will output instead of return data. What you can do is output buffer the include which would look something like: // Start buffering any output ob_start(); // Output the include into the buffer. include( 'horo-header.php' ); // Append the buffered output into the $content variable $content .= ob_get_clean(); Additionally, you may want to look into `get_template_part()` instead of include. For more information regarding output buffering please review the PHP docs: <
stackexchange-wordpress
{ "answer_score": 0, "question_score": 1, "tags": "filters, templates" }
WooCommerce related product - only show from primary category I have products in multiply categories e.g. `"All lamps"`, `"Ceiling lamps"` and `"Black lamps"`. `"Black lamps"` is the primary category (using Yoast SEO for making primary category). My problem is that related products show products from all selected categories. Is it possible to have related products only show from the primary category?
Thanks Leonardo for linking to solution here <
stackexchange-wordpress
{ "answer_score": 0, "question_score": 0, "tags": "woocommerce offtopic, plugin wp seo yoast" }
is_admin returning false in backend in server side rendered block I have a server side rendered block that lists cards with page thumbnails and the title wrapped in a link. I want that the link only gets a href when I'm in the frontend so I avoid clicking on the cards by mistake in the backend and getting redirected to the card page. Here is my code: $link = is_admin() ? "" : " href='" . get_permalink($post->ID) . "'"; echo <<<CPTItem <div class="cpt-list-item"><a class="cpt-list-item__link" $link> CPTItem; Unfortunately is_admin() is returning false in the backend in the block itself. I really don't know why, the only thing I can think about is that it's because the block is server side rendered. Is there a way around?
If you have a server side rendered block in the backend, it is rendered via the REST API endpoint `/wp/v2/block-renderer/xyz/blockname`. This endpoint calls your render function. In the frontend the render function is called directly. The function `is_admin()` checks if a backend page was requested. In a REST API Request is no backend page, so the function returns `false` on REST API requests. Instead you can check, if it is a REST API request via: if ( defined( 'REST_REQUEST' ) && REST_REQUEST ) { return 'Backend'; } else { return 'Frontend'; };
stackexchange-wordpress
{ "answer_score": 9, "question_score": 5, "tags": "php, block editor" }
How to get the Page featured image, not the Post featured image I currently have in my header.php: <?php $backgroundImg = wp_get_attachment_image_src( get_post_thumbnail_id($post->ID), 'header-large' ); ?> <?php if ( has_post_thumbnail() ) { ?> <div id="wrapper-navbar" itemscope itemtype=" style="background-image: url('<?php echo $backgroundImg[0]; ?>');"> <?php } else { ?> <div id="wrapper-navbar" itemscope itemtype=" <?php } ?> Which sets the background image if there is a featured image on the pages and posts. If there is none then there is a fall back where I have a default background image. My problem arises on the Blog page - The page which is set as the "Posts Page' The background image displayed on the "Posts Page" is the featured image of the latest Post on the list, NOT the featured image I have set for the page. How do I display the featured image of the Page and not of the latest post on the list?
You might be able to do this by calling `wp_reset_postdata();` otherwise you will need to get the blog page ID and set that on the line before instead: if ( is_home() ) {$post_id = get_option( 'page_for_posts' );} else {$post_id = $post->ID;} $backgroundImg = wp_get_attachment_image_src( get_post_thumbnail_id($post_id), 'header-large' ); ?> Note the `is_home()` is actually used for the blog page, as distinct from `is_front_page()` which is actually for the "homepage".
stackexchange-wordpress
{ "answer_score": 1, "question_score": 0, "tags": "header image" }
Facebook sharing image error with facebook debug I used to have Yoast as my main plugin but I have shifted to another plugin called SEO Press but then I have started having a problem that Facebook share is only fetching the resized smaller picture causing thumbnail to look small. I want to show an uncompressed full-size image as my featured image. Currently, it is only fetching irrelevant images such as sidebar ads image, and other stuff. Any help?
The problem was caused by "Hotlinking" option in cPanel and then SEO plugin in my wordpress. Fixing these two things, fixed my problems too.
stackexchange-wordpress
{ "answer_score": 0, "question_score": 0, "tags": "plugins, seo, facebook" }
Can I use REST API if the site is protected with .htpasswd is there a way to use Wordpress REST API if the site is protected with **AuthType Basic** using **htpasswd**?
You have to supply basic auth headers like below : curl -D- \ -X GET \ -H "Authorization: Basic xxxxyyyzzz" \ -H "Content-Type: application/json" \ " _"xxxxyyyzzz" is the username:password base64 encoded_
stackexchange-wordpress
{ "answer_score": 0, "question_score": 0, "tags": "rest api" }
Executing Javascript when a New Post is Published I thought it was simple, but I can’t do it. I’ve been totally stuck for five days I want to be able to trigger the Javascript console.log() function when a new post is published function display_console_log() { echo " <script> console.log('New post published') </script> "; } add_action('auto-draft_to_publish', 'display_console_log'); I don’t understand what’s wrong with this code Thank you in advance to those who will help me
Your code depends on the post being in an `auto-draft` state immediately before publication, which isn't guaranteed. For a more generic option, try using the `transition_post_status` hook: function display_console_log( $new_status, $old_status, $post ) { // Only runs if the post is transitioning from a not-published state // to the `publish` state. if ( 'publish' !== $old_status && 'publish' === $new_status ) { echo " <script> console.log('New post published') </script> "; } } add_action( 'transition_post_status', 'display_console_log', 10, 3 ); (Also, tangentially related, it's not in keeping with the WordPress Way to inject JavaScript code directly; I recommend reading up on how and why to use `wp_enqueue_script()`.)
stackexchange-wordpress
{ "answer_score": 0, "question_score": 1, "tags": "plugins, javascript" }
Is there an option to execute javascript file only on plugin activation I'm creating a custom plugin for WordPress and I'm trying to execute `javascript` file only once right after plugin activations. I'm using `register_activation_hook()` and `wp_enqueue_script()` to execute file only once when the plugin is activated. There are no errors in the code since the `javascript` code works well if it is called outside the `register_activation_hook()`. This is what I've tried so far: register_activation_hook( __FILE__, 'full_install' ); function full_install() { function rest_api() { wp_enqueue_script('activation_data_api', plugins_url('assets/js/activation_data_api.js', __FILE__)); } add_action( 'admin_enqueue_scripts', 'rest_api' ); } In the end, the plugin needs to execute `javascript` file only once right after activation.
Here is the solution: register_activation_hook( __FILE__, 'rest_api_hook' ); /** * Runs only when the plugin is activated. */ function rest_api_hook() { /* Create data */ set_transient( 'rest_api', true, 5 ); } /* Add notice */ add_action( 'admin_notices', 'rest_api_hook_exec' ); /** * Rest API Notice on Activation. */ function rest_api_hook_exec() { /* Check transient, if is available display notice */ if( get_transient( 'rest_api' ) ) { // Execute script wp_enqueue_script('activation_data_api', plugins_url('assets/js/activation_data_api.js', __FILE__)); // Delete script after executing delete_transient( 'rest_api' ); } }
stackexchange-wordpress
{ "answer_score": 0, "question_score": 0, "tags": "php, plugin development, hooks" }
post body class for current user only if they are the post author I'm trying to find a way to add a body class "author" IF the current user is the author of the post they are viewing. This is what I have so far... add_filter( 'body_class','my_body_classes' ); function my_body_classes( $classes ) { if ( !$current_user->ID == $post->post_author ) { $classes[] = 'post-author'; } return $classes; }
The code isn't working because you haven't defined or retrieved the `$current_user` or `$post` variables from anyway. You've also got a `!` here for some reason: `!$current_user->ID`, which will just break the condition. You need to use the appropriate functions to get their values, and also use `is_single()` to make sure you're viewing a single post (otherwise the post author could be missing or something unexpected). add_filter( 'body_class', function( $classes ) { if ( is_single() ) { $post = get_queried_object(); $user = wp_get_current_user(); if ( $user->ID == $post->post_author ) { $classes[] = 'post-author'; } } return $classes; } );
stackexchange-wordpress
{ "answer_score": 1, "question_score": 0, "tags": "custom post types, author, body class" }
Wordpress replaces "https://" with "//" for Site & Wordpress-URL When I save "` in General Settings as my Site & Wordpress URL, it gets replaced by "`//example.com`". To analyze the problem, I checked the Wordpress database, but 'WP_HOME' and "WP_SITEURL" are correctly stored as "` Actually, this is not a big problem, but Yoast SEO also shows my canonical URL as "`//example.com`". So I need to fix that problem ...
WordPress doesn't do this on its own. It must be a plugin or a theme. The first step in trying to diagnose this would be to turn off all plugins and switch to a default theme, then start turning plugins back on, one by one, till you find the culprit. If none of your plugins are to blame, then it is probably the theme you were using.
stackexchange-wordpress
{ "answer_score": 0, "question_score": 0, "tags": "site url, plugin wp seo yoast, rel canonical" }
500 Error, Get custom field and returning it I am using this code but getting a 500 error on the `IF` part. Not sure why this happens. $instac = get_the_author_meta( 'au-instagram', $current_author->ID ); if (!empty($instac)) { return '<a href="' . $instac . '" class="kalim">instagram</a>' }
500 error or internal server error is probably caused by a PHP error. By enabling WordPress debug, you’ll easily find where the problem is. You can follow the instructions here < From your code, it’s easy, you’re missing a semi-column before the closing curly bracket.
stackexchange-wordpress
{ "answer_score": 0, "question_score": 0, "tags": "php, functions, 500 internal error" }
How to remove "Categories:" part after the post title? Im quite new to wordpress and trying to figure out the problem shown on the picture. Cant find the place to hide it.Thanks! ![enter image description here](
It depends on the Wordpress theme you're using. If you can find out what html class the category/post meta is under using Inspect Element, it will be easy to hide it via CSS. Otherwise you will need to find where the 'Post Meta Data' is being added in PHP inside your theme and remove it. For now you can try and paste the following code inside your style.css file and see if it works, but it's just guessing at this stage: footer.entry-footer, .entry-meta { display: none; }
stackexchange-wordpress
{ "answer_score": 0, "question_score": 0, "tags": "categories" }
Exclude authors IDs from WP_Query I am using this code, trying to exclude specific authors from `WP_Query`, however the author IDs in the array are not being excluded. Any ideas please? <?php $args = array( 'meta_query' => array( array('who' => 'authors') ), array( 'author__not_in' => array(10, 3, 4) ) ); $site_url = get_site_url(); $wp_user_query = new WP_User_Query($args); $authors = $wp_user_query->get_results(); ?>
> exclude specific authors from `WP_Query` You can do it like so: $args = array( 'author__not_in' => array( 10, 3, 4 ), ); $posts_query = new WP_Query( $args ); But if you meant "from `WP_User_Query`", then in `WP_User_Query`, you should use the `exclude` parameter, and that `array('who' => 'authors')` shouldn't be in `meta_query`: $args = array( 'exclude' => array( 10, 3, 4 ), // not author__not_in 'who' => 'authors', // not in meta_query ); $users_query = new WP_User_Query( $args ); For the full list of parameters, refer to `WP_User_Query::prepare_query()` for `WP_User_Query`, or `WP_Query::parse_query` for `WP_Query`.
stackexchange-wordpress
{ "answer_score": 1, "question_score": 0, "tags": "wp query, functions, author" }
how to show Author post type count I have multi author wordpress site and every author can publish posts from two different post types . i want to display author post count by post type in author.php . According to codex.wordpress i used this code: but it displays total post count instead of author post count. <?php echo 'Number of posts published by user: ' . count_user_posts( $userid , "book" ); ?>
This solved $author_id = get_queried_object_id(); //get author id echo 'Number of posts published by user: ' . count_user_posts( $author_id , "custom-post-type" ); ?>
stackexchange-wordpress
{ "answer_score": 0, "question_score": -1, "tags": "custom post types, users, author, count" }
Exclude admin from WP_Query Contributors We are using this code to get a list of all contributors but we would like to exclude the admin from this list. Currently the admin and any role above the contributor role is being shown with this code. $args = array('exclude' => array( 10, 18, 4, 15, 9 ), 'who' => 'contributors' );$wp_user_query = new WP_User_Query($args);
I realize now that you're not talking about WP_Query but _WP_User_Query_. Looking at the documentation for WP_User_Query it says this about the `who` parameter: * **who** _(string)_ \- Which users to query. **Currently only 'authors' is supported. Default is all users.** Instead you can use the role parameter and exclude certain users by ID like so: // Grab all contributors $contributor_ids = new WP_User_Query( array( 'role' => 'contributor', 'exclude' => array( 10, 18, 4, 15, 9 ) ) ); You can also pass multiple roles to the above. For more info check out the section on roles.
stackexchange-wordpress
{ "answer_score": 2, "question_score": 1, "tags": "wp query, functions" }
Can't get ID of post that relates to the comment I added custom checkbox to the comment form. I am trying to write the post ID of this comment in the database. But without success. I'm trying with something like this: add_action( 'comment_post', 'save_chbox_in_db' ); function save_chbox_in_db() { $post_id = ??? // Can't get id... insert_to_db ( $email, $post_id ); // custom function } I tested these options: global $post; $post_id = $post->ID(); global $wp_query; $post_id = $wp_query->post->ID; $post_id = get_queried_object_id(); $post_id = get_the_ID(); As a result, I get zero or nothing. Where is the problem? Something with "comment_post" action? Or do I make some stupid mistake?
`comment_post` hook pass to attached functions 3 parameters. The fourth parameter of `add_action()` indicates to how many parameters the attached function will be able to access. add_action( 'comment_post', 'save_chbox_in_db', 10, 3 ); function save_chbox_in_db( $comment_ID, $comment_approved, $commentdata ) { $post_id = (int)$commentdata['comment_post_ID']; // // other code // }
stackexchange-wordpress
{ "answer_score": 2, "question_score": 0, "tags": "hooks, comments" }
Wordpress Codex has different number of arguments for get_previous_post and get_next_post functions. Why? Compare the following two links: < < The get_previous_post function **doesn't** have the last $taxonomy parameter, while get_next_post has it listed. I followed those instruction literally, which caused my get_previous_post to break. When I noticed the difference between the two functions, I tried specifying the taxonomy in my get_previous_post function, which fixed the problem. Is this a mistake in the Codex for get_previous_post?
The Codex does not document the `$taxonomy` argument. Without digging into it, my assumption would be that maybe it originally was not one of the arguments and no one ever bothered to change the Codex. The Codex, while still a tremendous resource of information, is (1) user generated/curated content and can be prone to mistakes, and (2) is no longer the "official" documentation of WP core functions, hooks, and APIs. That status belongs to < On the developer site, the `$taxonomy` argument IS documented for `get_previous_post()`. Since that data literally comes from the WP core inline documentation, that right there tells you that the Developer Docs are correct and the Codex is wrong. See: * < * <
stackexchange-wordpress
{ "answer_score": 2, "question_score": 1, "tags": "codex" }
Wordpress posts loop pagination - first page return 125 posts instead of 10 and the rest return 10 I'm trying to show 10 posts per page with pagination on WordPress and the first page return 125 posts instead of 10 and the rest of the pages return 10 posts as requested, please assist :) $paged = (get_query_var('paged')) ? get_query_var('paged') : 1; $output = array(); global $post; $args = array('nopaging' => false, 'paged' => $paged, 'posts_per_page' => 10, 'post_type' => 'post', 'order'=> 'DES', 'orderby' => 'date'); $postslist = new WP_Query( $args ); if ( $postslist->have_posts() ) : while ( $postslist->have_posts() ) : $postslist->the_post(); array_push($output, array("timestamp" => get_the_date('U'),"img_url" => get_the_post_thumbnail_url(), "title" => get_the_title(), "text" => get_the_content())); endwhile; wp_reset_postdata(); endif;
The sticky posts was the problem, Thanks to @Michael answer, I have excluded the sticky_posts from the query 'ignore_sticky_posts' => 1
stackexchange-wordpress
{ "answer_score": -1, "question_score": 0, "tags": "posts, loop, pagination" }
Issue with theme mod options during domain migration I want to migrate my development wordpress site to the production domain. In order to success the migration I found and replace all previous url occurences (< to the new (< The problem is that old urls cannot be replaced directly in the field `option_value` of `theme_mods_{your theme name}` in the table `wp_options` because data in there are serialized. How can I replace old urls by the new without breaking theme settings ?
It's possible to search and replace old urls to new ones by using `maybe_unserialize(get_theme_mods())` and `get_theme_mod()` WP functions and following these steps: 1. Create a php file in the root folder of your WP installation (same path as `wp-load.php`). 2. Insert the following code : require_once("wp-load.php"); $r = maybe_unserialize(get_theme_mods()); foreach ($r as $k => $v){ if(!empty($k)){ $ListOptions[] = $k; } } foreach($ListOptions as $option){ $str = get_theme_mod($option); $str = str_replace(' ' $str); $str = str_replace('http:\\/\\/localhost', 'https:\\/\\/mediadroit.fr', $str); set_theme_mod($option, $str); var_dump('|'.$option.': '.get_theme_mod($option).' ===> '.$str); echo "\n"; } 3. Execute the script
stackexchange-wordpress
{ "answer_score": 0, "question_score": 0, "tags": "themes, migration, theme options, get theme mod" }
Do I need to escape number in this shortcode function? This is the function: function shortcode_output($atts) { return do_shortcode('[ks_tab col="'.$atts['num'].'"][/ks_tab]'); } add_shortcode( 'my_shortcode', 'shortcode_output'); People would add a number (only number) when using my shortcode, do I need to escape it so that it accepts only numbers?
**Yes, never trust user's input.** Just because you told people to provide a valid number for a specific shortcode parameter, it doesn't guarantee that the input will always be a valid number, so always secure user's input — and output. You should also, if you haven't already done so, read these articles: * Data Validation * Securing Input * Securing Output And for example in your case, for accepting absolute integers only: <?php $cols = absint( $atts['num'] ); // Validate and set default value. $cols = $cols ? $cols : 3;
stackexchange-wordpress
{ "answer_score": 1, "question_score": 0, "tags": "shortcode" }
add_action('init') not work my code is add_action('init', 'user_logged_in'); function user_logged_in(){ if( is_user_logged_in() && is_page('login')){ wp_redirect(home_url()); exit; } } the page slug and name is "login" I do not want the logged in member to access the login page. But this code does not work in functions.php. Can you tell me what went wrong?
I believe `init` is too early to determine `is_page()`. Try a later hook, like `template_redirect`. function wpse_344136_user_logged_in(){ if ( is_user_logged_in() && is_page( 'login' ) ){ wp_redirect( home_url() ); exit; } } add_action( 'template_redirect', 'wpse_344136_user_logged_in' );
stackexchange-wordpress
{ "answer_score": 1, "question_score": 0, "tags": "login, actions, init" }
Displaying SQL query result from user input via wpdb I'm a bit stuck with one of my task which is to require a user input for an 'ID no' and it shall go through a table in my WP and display the result on the same page (after hitting Submit). I'm currently using the Code Snippets plugin to insert this PHP code into one of my WP page. However, as of now, when I input a valid IC/ID no. into the input field, it doesn't seem to return anything. Am I doing something wrong on the form part? Please enlighten. Thanks! <?php $name=$_POST["ICNo"]; global $wpdb; $resultsap = $wpdb->get_results('SELECT * FROM `wp_apelc_users` WHERE `icno` = .$name.'); foreach($resultsap as $row) { echo 'Name: '.$row->name.', Status: '.$row->status.'<br/>'; } ?> <form method="post"> <div> Your IC No: <input type="text" name="ICNo"> <input type="submit" name="submit" value="Submit" > </div> </form>
> use this snippet it works <?php if(isset($_POST["ICNo"])) { global $wpdb; $name = $_POST["ICNo"]; $resultsap = $wpdb->get_results( $wpdb->prepare( "SELECT * FROM wp_apelc_users WHERE icno = %s", $name ) ); foreach ($resultsap as $row) { echo 'Name: ' . $row->name; } } ?> <form method="post"> <div> Your IC No: <input type="text" name="ICNo"> <input type="submit" name="submit" value="Submit" > </div> </form>
stackexchange-wordpress
{ "answer_score": 0, "question_score": 0, "tags": "php, wpdb, code" }
What is an endpoint for custom post type comments in REST API? In my react project i am using worpdress as backend and need to use my custom post type `events` comments also. So as per the WordPress documentation for comments API i am using an endpoint like this “`/wp/wp-json/wp/v2/comments?events=704`”; so according to this it should display only 704 post-ids comments. But in my case it returns me all the comments which are posted in the `post_type = post` also. See below JSON result of the above API endpoint for custom post type. ![enter image description here]( Here is a `'post_type' => post` comment's data that returns a correct result. ![enter image description here]( I have passed this argument in the register_post_type 'show_in_rest'=> true
Custom post types are still posts, so to retrieve comments for a specific post of a custom post type you use the `post` argument. From the API reference: > `post` Limit result set to comments assigned to specific post IDs. So: json/wp/v2/comments?post=704
stackexchange-wordpress
{ "answer_score": 1, "question_score": 0, "tags": "rest api" }
How do I add class to an admin comment? When I customize the wp_list_comments() output, how do I add a class to the admin comments? Relevant code: <?php wp_list_comments( array( 'style' => 'ol', 'callback' => 'custom_list_comments' ) ); ?> * * * <?php if( ! function_exists( 'custom_list_comments' ) ): function custom_list_comments( $comment, $args, $depth ) { ?> <li id="comment-<?php comment_ID() ?>"> <?php echo get_avatar( $comment, 48 ); ?> <?php comment_text(); ?> <span><?php echo get_comment_author() ?></span> <time><?php comment_time(); ?></time> <?php comment_reply_link( array_merge( $args, array( 'depth' => $depth, 'max_depth' => $args['max_depth'] ) ) ); ?> <?php edit_comment_link(); ?> <?php } endif;
One way to add some custom class to a `li` tag if the comment was posted by an administrator is to replace line `<li id="comment-<?php comment_ID() ?>">` with `<li <?php comment_class(); ?> id="comment-<?php comment_ID() ?>">` This will add support for the default WP comments classes to your comments callback. Once you do that add in your theme functions.php file the code below it will add class "posted-by-admin" to the `li` tag classes if the comment author is an administrator. add_filter( "comment_class", function( $classes, $class, $comment_id, $comment ) { if( $comment->user_id > 0 && $user = get_userdata( $comment->user_id ) && user_can( $comment->user_id, "administrator" ) ) { $classes[] = "posted-by-admin"; } return $classes; }, 10, 4 );
stackexchange-wordpress
{ "answer_score": 3, "question_score": 0, "tags": "comments" }
Expired event redirect to parent category I build a website for a client of mine, that is going to continuously host events for his area. One of the requirements he has is to expire and remove from the database the events already completed. The events will belong to `categories`. The question is, how I could redirect with `301` the search engines and the visitors to the parent category of each event? So let's say we have the categories `theater` and `concert`. If I have an even for theater, and the event is expired + removed from the DB, how can I make the redirect to the `theater` category for all the upcoming visitors? Any idea? * * * # Update What if I make a custom table to record the slugs of the events and the category IDs when an event is deleted, and then when I have a 404, to check the DB table for the requested slug and make a redirect using the category ID? Could that solution be performant given that the site is going to host a few million of events?
Since I have less reputation I can't comment, this is not answered with code but wanted to help, you may check this plugin: < or just take required code from the plugin ( I am not connected with that plugin anyway )
stackexchange-wordpress
{ "answer_score": 1, "question_score": 0, "tags": "taxonomy, redirect, 404 error" }
Elfsight Google Maps Plugin Version 2.1.0 : Location image input not found I'm using Elfsight Google Maps Plugin Version 2.1.0 in my WordPress website to create an interactive map. 1- I can’t find the image field in the description section like in the demo to upload an image to my location, and i get google building image by default for every location i create. 2- Also the pointer doesn't load i must enter "plus codes" instead of address so the location can be loaded. Can anyone help me with that?
this plugin Pods – Custom Content Types and Fields triggered a conflict with the Elfsight Google Maps Plugin and cause a problem with the image and address fields, uninstall it and the map will work perfectly.
stackexchange-wordpress
{ "answer_score": 0, "question_score": -1, "tags": "plugins, google maps" }
YOAST SEO won't work on custom post type archive I created my custom post type page (archive-objects.php). This page works fine, I have been created page for it and attributed template to it. So everything is okay. But something wrong is with YOAST SEO. This page title, img and other iformation taking from not this page info, but from first looped post in this archive. In my custom post type I done public -> true and has_archive -> true. What problem can this be? Thank you.
I just find out what I was missing at the top, after get_header();. <?php if (have_posts()) : while (have_posts()) : the_post(); ?> and at the bottom, just before get_footer(); <?php endwhile; ?> <?php endif; ?> So I just figured out that I was not loading archive properly, so I don't get all his information.
stackexchange-wordpress
{ "answer_score": 1, "question_score": 0, "tags": "custom post types, posts, seo, customization" }
Warning , Use of undefined constant PLUGIN_PATH? I having a warning in my error log > Use of undefined constant PLUGIN_PATH - assumed 'PLUGIN_PATH' (this will throw an Error in a future version of PHP) When I googled it I couldn't find the answer but seems a lot of websites are showing up this warning publically? add_filter('single_template', 'my_custom_template'); function my_custom_template($single) { global $post; /* Checks for single template by post type */ if ( $post->post_type == 'POST TYPE NAME' ) { if ( file_exists( PLUGIN_PATH . '/Custom_File.php' ) ) { return PLUGIN_PATH . '/Custom_File.php'; } } return $single; } This was the code that I used: Custom Post Type Templates from Plugin Folder? any fix?
The error is self explanatory: `PLUGIN_PATH` is not defined anywhere. It is not one of WordPress' default constants (which are listed here, and all start with `WP_`). In the context of the code you've copied, it's apparent that it was either supposed to be replaced with the path to your plugin (in which case using a constant in the example code was a bad idea), or it used to exist (the answer is 8 years old). This is mentioned in the comments on your own link. To get the path to a plugin file (these days at least), you need to use `plugin_dir_path()`: if ( file_exists( plugin_dir_path( __FILE__ ) . 'Custom_File.php' ) ) { return plugin_dir_path( __FILE__ ) . 'Custom_File.php'; } Just be aware that `plugin_dir_path( __FILE__ )` returns the path to the current file, so if the file containing this code is in a subfolder of your plugin you need to account for that.
stackexchange-wordpress
{ "answer_score": 0, "question_score": 0, "tags": "custom post types, plugin development, templates" }
How to pass username in url I have several author page like > mysite.com/author/username1 > mysite.com/author/username2 I want to create a dynamic url like > mysite.com/author/current_loggedin_username How to create this.
First, you should check if the user is logged in - use is_user_logged_in(). Next step is to get ID of current user with get_current_user_id(). Next, get the URL for the author with the given ID using get_author_posts_url(). The last step is to display the button with the link. if ( is_user_logged_in() ) { $uid = get_current_user_id(); $link = get_author_posts_url( $uid ); printf( '<div><a href="%s">My posts</a></div>', $link ); } You can insert such a code in the `header.php` file or add it as a function to `functions.php` file and call this function in the `header.php`.
stackexchange-wordpress
{ "answer_score": 0, "question_score": 0, "tags": "url rewriting, parameter" }
How to retrieve the post featured image (thumbnail) ID in Gutenberg blocks? WordPress (PHP) has a lot of functionality to retrieve the post featured image (post thumbnails). However I can't find easy ways to retrieve the post featured image in a dynamic block. ## Using PHP: get_post_thumbnail_id(); // <-- Post Thumbnail ID * * * ## Using WordPress REST API: edit: withSelect( function( select ) { return { post_id: select( 'core/editor' ).getCurrentPostId(), post_type: select( 'core/editor' ).getCurrentPostType() }; } )( function ( props ) { wp.apiFetch( { path: '/wp/v2/' + props.post_type + 's/' + props.post_id + '?_embed' } ).then( function( post ) { console.log( post._embedded["wp:featuredmedia"][0].id ); // <-- Post Thumbnail ID } ); return el( 'div', null, '[Block Placeholder]' ); } ),
I think you're looking for: const featuredImageId = wp.data.select( 'core/editor' ) .getEditedPostAttribute( 'featured_media' ); to get the ID of the featured image and then for the corresponding media object: const media = featuredImageId ? wp.data.select( 'core').getMedia( featuredImageId ) : null; See e.g. here in the post featured image component: <
stackexchange-wordpress
{ "answer_score": 3, "question_score": 1, "tags": "post thumbnails, block editor" }
How can I set a Post's default visibility to private and pending review checked there are 2 things I'd like to do: 1\. set a post's visibility to private by default. I've been looking around the web for a code or even a plugin that lets me do this. The problem I've run into is that the codes no longer work. 2. set the pending review checkbox to true as well? If someone can point me in the right direction, Id appreciate it. Thank you ![enter image description here](
Found this snippet after more searching: //Force posts of custom type to be private //…but first make sure they are not 'trash' otherwise it is impossible to trash a post function force_type_private($post) { if (($post['post_type'] == 'post') { if ($post['post_status'] != 'trash') $post['post_status'] = 'private'; } return $post; } add_filter('wp_insert_post_data', 'force_type_private'); Changed the boolean to: if (($post['post_type'] == 'post')&&(!current_user_can('administrator'))) This makes sure only admin can publish.
stackexchange-wordpress
{ "answer_score": 1, "question_score": 1, "tags": "posts, post status" }
Making a child theme in order to update the parent theme I'm really new to Wordpress development and had made a mistake by changing a parent theme for customizations instead of customizing a child theme. Not i cannot use the updates that my theme provider provides. Is there a way to fix this? Theme has WPbakery page builder as the primary building extension.
From my answer to I modified the parent theme without creating a child theme (similar question) > As stated in a comment, any changes you made to the parent theme will get overwritten with the theme update. > > But, you could copy all of the parent theme code to a new theme folder, adjust the theme header on the copy to make it a child theme. You could activate the copied theme, or make it a child theme, and then dig out the changes you made to the theme. Put those changes in another theme folder, adjusting it to a new child theme name, then activate that new (2nd) child theme. > > All of this is a cautionary tale about the importance of child themes.
stackexchange-wordpress
{ "answer_score": 0, "question_score": 0, "tags": "child theme, parent theme" }
What is the difference between get_permalink vs get_the_permalink? What is the difference between get_permalink vs get_the_permalink?
Nothing. `get_permalink()` is the original function, and is used to get the permalink URL for a post. `get_the_permalink()` was introduced in 3.9 simply so the permalink function was consistent with the other post-related template tags, such as `get_the_title()`, `get_the_content()`, which are all prefixed with `get_the_`. The equivalent functions for echoing the result of those functions are the same but without the `get_`, such as `the_title()`, but in the equivalent for `get_permalink()` is not `permalink()`, it's `the_permalink()`, so the lack of `get_the_permalink()` was an inconsistency. Using the function just calls `get_permalink()`, which still exists for backwards compatibility reasons, so the result will be exactly the same.
stackexchange-wordpress
{ "answer_score": 16, "question_score": 7, "tags": "permalinks" }
How to extend the URLPopover render settings for the paragraph Gutenberg block? Add this moment when you enter an URL in a Paragraph-block there is only one setting: Open in New Tab. I like to be able to add settings such as Link Style. That adds a class to a link.
**It cannot be done, no API currently exists to add what you want to add.** If we look at the component that implements this: < The `InlineLinkUI` wraps a component that wraps the `URLPopover` component, and places a child component inside it which is how the new window checkbox is added. No slots are present or hooks for intercepting this. Judging from what you want to do, I don't think this is the intended path forward. Instead, build a block, or a new inline block. You can also open an issue on the Gutenberg GitHub requesting the feature
stackexchange-wordpress
{ "answer_score": 0, "question_score": 0, "tags": "block editor" }
How to Include a Loop Template File in a Plugin I am trying to include a template file into a loop i made in a shortcode, in a plugin. Everything shows up fine when the template is actually pasted into the loop, but to make things neat I want to separate it into it's own file. I created a file called `hi.php` and it's located in a plugin subfolder called `parts`. Here is the code I place in the loop, but it is not loading the template: `include plugins_url( '/parts/hi.php', __FILE__ );`
I do it like this: // Inclusion of additional php files define( 'MYPLUG_DIR', plugin_dir_path( __FILE__ ) ); require_once( MYPLUG_DIR . 'hi.php' ); It lets you use that more easily if you have to include several files.
stackexchange-wordpress
{ "answer_score": 2, "question_score": 1, "tags": "plugins, php, templates" }
Non-Blog Website without Search: are comments.php and search.php in theme still required? What is the best practice when it comes to a static, minimal WP website? It will have no blog updates, no discussion/comments, and no search. Should all the standard template files still be included?
According to the documentation, the only _required_ files in a theme are `style.css` and `index.php`. All other files are optional. You can use the ones you need and discard the ones you don't need. If you haven't seen it, I'd recommend you check out WordPress's developer site on the topic of themes.
stackexchange-wordpress
{ "answer_score": 1, "question_score": 1, "tags": "theme development, search, comments template" }
Child theme blocks post from publishing I created a child theme to another template, which introduces custom post type with loads of custom fields and specialized functions. Notes: 1. I did not touch anything in the custom post type logic 2. Only change, apart from usual child theme `style.css` and `functions.php` to load parent style is to introduce different logic of `search.php` to display only that custom post type in search results However, when I load that child template, I am unable to publish a new post of that custom post type. Updating current posts work, but clicking "Publish" button does nothing. Saving draft works. Where should I look, apart server logs (which are empty) in order to resolve this?
I assume it's only the child-theme which encounters this error - and therefore it is probably a small error - but not seeing any errors in the logs makes it harder to determine exactly where the error is. First of all, I would suggest you turn on your WP_DEBUG in the wp-config.php, maybe there's an error you're missing. You can find more information on the WP_DEBUG define here. If no errors are shown, please check your console for any errors (Right click > Inspect > console tab). I'm certain there's an error either by activating WP_DEBUG or checking the console. I have experienced this error before, and whenever I was saving a post, there was an AJAX-error occuring. I fixed this by starting over with the child-theme, as I must have forgot something.
stackexchange-wordpress
{ "answer_score": 1, "question_score": 0, "tags": "custom post types, child theme" }
how to SELECT meta values that are not null? I have a rating system for our products but there is an issue: by the code, that will SELECT all comments in `commentmeta` table that have `rating` as `meta_key`. even those who do not have a rate (the user did comment but did not leave a rating for the product). **so I need to SELECT just those comments that the`rating` as meta_key is not NULL.** my current code: $sql = $wpdb->prepare( " SELECT meta_value FROM {$wpdb->prefix}commentmeta INNER JOIN {$wpdb->prefix}comments ON {$wpdb->prefix}commentmeta.comment_id = {$wpdb->prefix}comments.comment_ID WHERE comment_post_ID = %d AND meta_key = 'rating' ", get_the_ID() ); $results = $wpdb->get_results( $sql ); Thanks for helping me
I founded myself my searching: $sql = $wpdb->prepare( " SELECT meta_value FROM {$wpdb->prefix}commentmeta INNER JOIN {$wpdb->prefix}comments ON {$wpdb->prefix}commentmeta.comment_id = {$wpdb->prefix}comments.comment_ID WHERE comment_post_ID = %d AND meta_key = 'rating' AND meta_value IS NOT NULL AND meta_value <> '' ", get_the_ID() ); $results = $wpdb->get_results( $sql );
stackexchange-wordpress
{ "answer_score": 0, "question_score": 0, "tags": "sql, select, meta value" }
Changing link format from Calendar widget I have the Calendar widget in the sidebar of my wordpress site. It currently links to each day's post using the date format such as "/2019/08/01/" instead of the permalink setting (post name). How can I change it to use the permalink setting? The post page displays differently when the link has only the date format and I don't want google indexing the posts twice.
The calendar widget doesn't link to "each day's post". It's linking to an archive page that lists all posts made on that date. Hence the `/2019/08/01/` URL. If you click the post title (or "Continue Reading" or "Read More" link if there is one) you will be taken to the single post whose URL will match your settings. If you've only ever made one post per day, then the date archive for a specific day will only show one post, but if you make more than that the date archive will show multiple posts on the same page. The purpose of the calendar widget is to provide links to these date archives. If you want one that links directly to individual posts, you'll need to find a 3rd-party alternative.
stackexchange-wordpress
{ "answer_score": 0, "question_score": 0, "tags": "permalinks, calendar" }
Can't get woocommerce_get_price_html to work I'm building a function to interact with the price html block in wordpress. This is my code add_filter( 'woocommerce_get_price_html', array( $this, 'get_price_html' )); public function get_price_html( $product ) { echo '<a href="my-price">' . $product->get_price() . '</a>'; } It's not working. What's wrong?
I think your are missing parameters (even if you're not using those) as per its definition and always try to `return` into filters instead of `echo` the value. Try the following: add_filter( 'woocommerce_get_price_html', array( $this, 'get_price_html' ), 10, 2); public function get_price_html( $price_html, $product ) { return '<a href="my-price">' . $product->get_price() . '</a>'; }
stackexchange-wordpress
{ "answer_score": 0, "question_score": 1, "tags": "plugin development, woocommerce offtopic, filters" }
search filter add priority to post_type and add order to some post_type I don't want to change the core SEARCH function. I have default search function and only updating `search.php` file in the theme. I added search_filter function into functions.php. function search_filter($query) { if (!is_admin() && $query->is_main_query()) { if ($query->is_search) { $query->set('post_type', array('page', 'post', 'fsgallery')); $query->set('order', array('post_date' => 'DESC')); } } } add_action('pre_get_posts', 'search_filter'); I have 3 post_type in my Wordpress and I want to show all page result first and then combine POST and GALLERY results with ordered by date. Right now order by DESC result shows everything by ordered and could not show page first. What I need is: I want to show all page result first. After that I want to show post and gallery ordered by date.
Here is the code from the provided link after adaptation. add_filter( 'posts_orderby', 'se344727_custom_search_order', 10, 2 ); function se344727_custom_search_order( $orderby, $query ) { global $wpdb; if (!is_admin() && $query->is_main_query()) { if ($query->is_search) { // -- sort by: type, title, date -- // " ELSE 2 END ASC, " . $orderby; // -- sort by: type, date -- // " ELSE 2 END ASC, {$wpdb->prefix}posts.post_date DESC; $orderby = " CASE WHEN {$wpdb->prefix}posts.post_type = 'page' THEN 1 " . " ELSE 2 END ASC, " . $orderby; } } return $orderby; }
stackexchange-wordpress
{ "answer_score": 0, "question_score": 1, "tags": "search" }
Custom post type, global categories — what’s the template name? The documentation for template hierarchy for custom post types (CPT) includes: 1. Either for the CPT itself (`archive-cptname.php`) 2. Or for custom taxonomies (`taxonomy-taxonomyname.php`) 3. Or for overall categories (`category-catname.php`) But it doesn't include the obvious "CPT, with global categories". What would that be? I tried something like `archive-cptname-categoryname.php`, but this doesn't work. Any pointers?
Because there's no such thing. If you use the same taxonomy for two or more post types then there isn't separate archives for each post type in that taxonomy's terms. There's a single archive for that taxonomy that lists posts of both post types. This might not work for built in taxonomies (categories and tags) though, as they are configured to only display posts. To display your post type on the category archive you'll need to use the `pre_get_posts` filter to add it: add_filter( 'pre_get_posts', function( $query ) { if ( $query->is_category() ) { $query->set( 'post_type', [ 'post', 'cptname' ] ); } } ); If you need separate archives for categories for each post type, then you need to register a separate taxonomy for your post type. Something like `cptname_category`. They won't share terms, but they will have separate archives.
stackexchange-wordpress
{ "answer_score": 2, "question_score": 0, "tags": "custom post types, custom post type archives" }
How to target parent product category and its children using WooCommerce? In WooCommerce, archive-product is the default template for all product categories. I want to create a new product category template for one parent category and all of its children. I've created a new template **archive-foo.php** Now I need to change the code inside **taxonomy-product_cat.php** and tell it to use archive-foo.php "if it's my parent category or any of its children". Here is my code inside **taxonomy-product_cat.php** : if (is_product_category( 'foo-category' ) || cat_is_ancestor_of(19, get_queried_object()->term_id )){ wc_get_template( 'archive-foo.php' ); } else { wc_get_template( 'archive-product.php' ); } Currently, it's working for the parent category, but none of its children. Any help would be greatly appreciated.
the WordPress function `cat_is_ancestor_of()` is made for WordPress categories, **but not** for WooCommerce product categories which is a custom taxonomy `product_cat`. For Custom taxonomies you can use WordPress `term_is_ancestor_of()` function like: term_is_ancestor_of( 19, get_queried_object_id(), 'product_cat' ) So in your code: if ( is_product_category( 'foo-category' ) || term_is_ancestor_of( 19, get_queried_object_id(), 'product_cat' ) ) { wc_get_template( 'archive-foo.php' ); } else { wc_get_template( 'archive-product.php' ); } This time it should work.
stackexchange-wordpress
{ "answer_score": 0, "question_score": 1, "tags": "custom taxonomy, woocommerce offtopic" }
Where does MonsterInsights put Google Analytics code? I have looked at all the file in my theme and its parent theme, including the header.php and footer.php, but I still can't find the Google Analytics it put in. Do you know how to find its location?
It doesn't change the theme itself. It uses a hook to insert the tracking code. View the source of one of your outputted front-end pages, and you'll see the JS injected in there somewhere.
stackexchange-wordpress
{ "answer_score": 1, "question_score": 0, "tags": "plugins, google analytics" }
Change text color dynamically in Wordpress I would like to have a transparent nav bar. On the landing page, there will be a slider with images of varying colors, so I would like to change the text color of menu items to contrast against each respective image. A solution I found here seemed ideal: < However, when I implement here in an HTML builder: < it outputs a totally different effect. Same code, same browser, so I'm assuming it's Wordpress? `mix-blend-mode: difference` also seems to have no effect when I've applied it to other selectors from the stylesheet. Is there a reason WP won't output the same as the codepen? I would love a pure CSS solution if possible. JS as a last resort is doable, but not preferable. I have found SASS solutions, but have no idea what to do with that.
If you inspect the text, you'll see that your theme's CSS is overriding your custom CSS. You have `h2 { color: white; }` but your theme has `.widget h2 { color: inherit; }` so "inherit" wins out. If you change your own CSS to `.widget h2 { color: white; }` it will override the theme. Incidentally, the markup here is quite overly complex; you might want to look into a simpler theme without quite so many nested divs.
stackexchange-wordpress
{ "answer_score": 1, "question_score": 0, "tags": "css, navigation" }
Custom admin page: How to save changes specific to users I created a custom admin page in Wordpress and it works as it should. I also figured out how to save things, and have it displayed on the website. What I just can't figure out is to save the changes to my custom admin page for that specific user. Said in another way, you have to, for example, enter your phone number in an input field, where this phone number should appear on the website. I can do that part myself, but when other users access my custom admin page, they have to enter their own and not what another user has entered.
Then save the data in the usermeta table, linked to each user, by `update_user_meta()` and `get_user_meta()` functions. `get_current_user_id()` gives you the $user_id to pass. Choose a $meta_key that wion't create conflict, preferrably with a unique prefix. Same rule as for keys for saving data in options table.
stackexchange-wordpress
{ "answer_score": 2, "question_score": 1, "tags": "php" }
Need help removing block of white space between footer widgets and footer This is the page in question: < There's a large space between the footer widget areas (which are empty) and the footer. Setting the theme to no footer widgets doesn't resolve the issue. Oddly, it only seems to occur on category pages. I've tried using the chrome inspector and setting various classes not to display using CSS - but nothing seems to work. Any help appreciated!
The issue is with the .block class assigned a css of min-height .magazine .block { min-height: 480px; } Please change the min-height to auto or remove the 'block' class from that div element
stackexchange-wordpress
{ "answer_score": 0, "question_score": 0, "tags": "css, widgets, footer" }
wpcli: Error on post_content or post_title if accents When I try to create a new post with accents width wp-cli (in windows 10 command, I got latest wp-cli) wp post create --post_title="Héllo" --post_type=page --post_content="Héllo world" I got error: > "Impossible to insert this post in database" It works fine when I replace the "é" by "e" wp post create --post_title="Hello" --post_type=page --post_content="Hello world" Any idea ?
See Cannot create a post with Latin characters in the title on Windows. > Using UTF-8 in PHP arguments doesn’t work on Windows for PHP <= 7.0, however it will work for PHP >= 7.1, as it was fixed as part of Support for long and UTF-8 path. A workaround for PHP <= 7.0 is to use the `--prompt` option: > > > echo "Perícias Contábeis" | wp post create --post_type=page --post_status=publish --prompt=post_title > It looks a bit as if this bug only affects the title. Have you tried that? And the post content doesn't matter? Then the following should work: echo "Héllo" | wp post create --post_type=page --post_content="Héllo world" --prompt=post_title
stackexchange-wordpress
{ "answer_score": 1, "question_score": 1, "tags": "wp cli" }
Sync plugin settings (wp_options table) on multiple environments How do you guys handle database changes, more specifically the settings (wp_options)? Im looking for something like, having a JSON file (or migration files bit similar like Laravel) with settings, that I can run after a deployment. For example once I install WooCommerce I have a list with default settings (presets) I want to use and import at once. But also once I add a new feature or plugin that I can migrate those settings across multiple environments. Would be cool if that JSON file (or settings file) is environment based. So I can use test payment method settings on local and live settings on production. And just run a command like wp migrate options or something in my deployment script, which sets all the correct settings for that environment. Is there something like that? Thanks in advance :)
This is a tricky one since even if you might get it to work with Core with plugins you never know if they also store data in files, custom tables, post types and so in. If you then only sync the options table you might get inconsistent/partial/broken states. Also you probably don't want to sync everything since some things like transients are on the options table but aren't really settings. This is a general problem with systems that store configuration in the database and even more so with WP since the data storage formats are somewhat fragile. If you search the web or this site you'll see that there have been plenty of questions and attempts of approaching this. But there is no general best practice solution to it. Having said that, concerning your specific request you can have a look at < which looks like it is unmaintained but might give you a head start on one possible approach.
stackexchange-wordpress
{ "answer_score": 0, "question_score": 0, "tags": "sync" }
How to add published date in product I have on my site some products. My plan is to show some deals. But I want to show also the published date of the deal, the date that i have published the deal. Like a blogpost shows the published date. What code can i use and where can i add it? Hope you can help me. The site is www.vakantie.guru, under accomodation there are some products where i refer to. I have tried to find in the other files which cope is used for the blogpost date, thought that same code could be used. But I can't find it in the files
$post_id = 12; echo get_the_date( 'Y-m-d',$post_id);
stackexchange-wordpress
{ "answer_score": 0, "question_score": 0, "tags": "date, publish" }
Does hooking into a plugin action / filter override the plugin's function for that hook? I have a question about how actions and filters interact with functions: I am currently using an event ticketing plugin for wordpress, there are built in validation rules that is already in the plugin (i.e. fields are all completed, number fields contain integers etc.). I want to write a function that 'extends' the existing plugin function. When I write my functions, does the existing plugin function for that hook still apply? Or would I have to copy over parts of that function I want to retain into my new one? Or does wordpress run both functions in some kind of sequence? If I wanted to write a validation that is the opposite of what is currently in the plugin function (i.e. number fields should contain an alphabetical character) how does a custom function overwrite a part of an existing function? Would I have to remove those lines in the plugin file itself? Thanks in advance.
It depends _entirely_ on the specific plugin and the specific hook. It's completely up to plugin developers what they want to allow other developers to do. They could allow developers to replace entire functions; to perform a custom action at the beginning, middle, or end of a function; to modify the result of a function; or none of the above. It's impossible to give a generic answer. The only way to know what you can do is to consult the developer documentation for the plugin, which will tell you what you can do. If that doesn't exist, reading the actual code of the plugin and looking for hooks is all you can do.
stackexchange-wordpress
{ "answer_score": 0, "question_score": 0, "tags": "plugin development, functions, hooks, customization" }
Moving button on Online Consulting theme I found a theme I really like: < Unfortunately, the "Read more" button is in a position I don't really like: ![enter image description here]( I would vastly prefer if the button was below the post. Sadly, I'm quite unfamiliar with wordpress and don't really know where to get started. I suppose this could be done using CSS? I'm hoping someone can point me in the right direction.
If you go into your Admin section, under Appearance > Edit CSS, you will be able to override the CSS of the theme. In order to find out what the class is, you might want to Inspect the control with Google Chrome's Developer Tools.
stackexchange-wordpress
{ "answer_score": 2, "question_score": 0, "tags": "css" }
How to use a variable (for wordpress postid) in other queries? I don't know php, I just edit it for my needs, please excuse my possible mis-use of terms. I think the fact I am searching for the wrong terms has made this difficult to find a solution for, which is why I am asking. Basically I need to define a postid, then use it multiple ways. $number = 455; So above you can see the number of a postid. Then within my templates I am using it as follows. echo get_the_permalink( '$number' ); How do I make that work? echo get_the_permalink( '455' ); ^ works fine, but it means me typing that id a lot.
When you use the variable, don't use the quotes. So it would be like: echo get_the_permalink( $number ); You can also use: echo get_permalink( $number ); or: the_permalink( $number ) _get_the_permalink()_ is an alias for _get_permalink()_.
stackexchange-wordpress
{ "answer_score": 0, "question_score": 0, "tags": "php" }
Wordpress manual restore not completely successful I have restore my blog after around 4 years. I had a backup of both the database and wordpress files. I restore the database and wordpress files. The only manual modification I did is that I changed every occurrence of the site url in the raw mysql dump to the ` that is where my blog is currently. Everything worked properly except that node of the post and page content is being shown. When I login as the administrator, I can see the content but when I view the post or page, i cannot see the content. For example, on this post, I can see the post title and tags but not the content. Also, I have noticed, even if I create a new page or post, I can't still see the content. Any reason this is happening ?
Problem seems strange since you can see the content in the backend but not able to see it in the frontend. So here are a few suggestions. 1. Try to save the permalink again? And try to clear the cache too. 2. Try to change the theme to any other basic theme available. Also when I tried to go to < , it's giving me internal server error.
stackexchange-wordpress
{ "answer_score": 1, "question_score": 1, "tags": "backup" }
What is deprecated_argument_run meant to do exactly? I found an odd hook in the WordPress documentation. `deprecated_argument_run` which has this "enlightening description". > Fires when a deprecated argument is called. I pretty much figured that much out from the hook name. What is this hook's intended use?
As @sally-cj already hinted at in his comment this is used for debugging purposes, helping developers by notifying them of the use of deprecated arguments in their codebase. In core this is for example used to alert people of wrong arguments when using the REST API: < But you could add your own function to that hook that does whatever you find useful - send a mail, log to a file,... * * * Core uses it inside the (private, so not intended for use by non core code) `_deprecated_argument` function. And that function `_deprecated_argument` is actually used all over the place in core, for example inside `get_the_author` to give one random example.
stackexchange-wordpress
{ "answer_score": 1, "question_score": 0, "tags": "hooks" }
How do I update a nested option? I use this command to get values of ez-toc-settings->auto_insert_post_types wp eval "print_r(get_option('ez-toc-settings')['auto_insert_post_types']);" and this prints out the correct values: Array ( [post] => post [page] => page ) Now, I try to modify that so I have only "post" value I tried with: wp eval "update_option('ez-toc-settings auto_insert_post_types', array('post'));" Infact I have no idea on **how to update a key value within a nested option**.
`wp option` does all you need. See `wp option patch` in particular. > Updates a nested value in an option. * * * Get a nested option value: $ wp option pluck ez-toc-settings auto_insert_post_types Set a nested option value (with an array): $ wp option patch update ez-toc-settings auto_insert_post_types '{"post":"post"}' --format=json
stackexchange-wordpress
{ "answer_score": 1, "question_score": 1, "tags": "wp cli, options" }
How to prevent users to download videos from lms website? I want to develop a wordpress lms website that support woocommerce payment gateways. I've found some themes and plugins like: learnpress, wplms and much more Some of them doesn't support uploading video in website (using third party websites like Vimeo or Youtube) and I don't want to use them. I want my website instructors upload their video lessons in my website and other users watch them online. The problem is all of plugins and themes that I've found doesn't prevent users to download videos. Please tell me is there any lms plugin or theme that prevents users from downloading the video? Thanks
I found this answer online which responds your question !enter image description here
stackexchange-wordpress
{ "answer_score": 1, "question_score": 1, "tags": "plugins, themes, video player" }
How do I deactivate widgets by name? I cna get list of widgets with wp widget list sidebar-1 | search | search-2 | 1 | {"title":""} | recent-posts | recent-posts-2 | 2 | {"title":"","number":5} | recent-comments | recent-comments-2 | 3 | {"title":"","number":5} | categories | categories-2 | 4 | {"title":"","count":0} | meta | meta-3 | 5 | {"title":""} I can deactivate meta plugins with: wp widget deactivate meta-3 My problem is: how can I get the id **meta-3** from widget list ? or any other method to deactivate some widgets like meta, recent-comments etc
Try using the `--fields` and `--format` parameter, e.g. wp widget list sidebar-1 --fields=id --format=json Docs: WP-CLI Commands `wp widget list`
stackexchange-wordpress
{ "answer_score": 1, "question_score": 0, "tags": "widgets, wp cli" }
How to stop a permalink redirecting to a page whit same slug but different permalink I have this CPT that has this permalink < and this other page < And going to < redirects me to < for some weird reason, can anyone help me? EDIT1: By the way i have "'has_archive' => false," in cpt code in functions.php EDIT2: As a test i changed the slug for < to < to test what happened and now < does not redirect to nothing but a 404 page, and the cpt page is published and public
Okay i think i solved it for myself, i still have a problem but is unrelated to this question so i might make a new question for that one. The problem was that what i had registered as the slug for the CPT was "area-cliente/%category%" when i removed the "/%category%" and added the %category% thing in the permalink menu whit the plugin "Custom Post Type Permalinks" it now works, it solves this question but leaves me whit another problem. TL;DR: don't put in the slug of a CPT %category% because it appears to not work
stackexchange-wordpress
{ "answer_score": 0, "question_score": 0, "tags": "custom post types, permalinks, pages" }
How to save history in the client's browser without login? I know that we can use some snippets or plugins to save the client history but this work for the login clients as I know. My question is how to do the same thing but for unlogin users. Let's say I am a user without an account and I have viewed some posts in the website. So the next time I want to visit this site I want to see my latest posts that I have seen from the last visit in a page called history. It's like YouTube history page but without login so that everything is saved in the user's browser like a cookie file or something else. To use cookies is easy if I followed the php documentation but I want to use it in wordpress so that why I am asking my question here.
You can use cookie to store information in the visitor's browser. In your single post template, you can set the cookie by using setcookie( 'last_post_id', get_the_ID() ); And on your other page, you can manage the last post that the user has visited. $last_post_id = ! empty( $_COOKIE['last_post_id'] ) ? $_COOKIE['last_post_id'] : false; if( $last_post_id ) { // do something with the cookie. }
stackexchange-wordpress
{ "answer_score": 0, "question_score": 0, "tags": "cookies, customization, browser compatibility" }
multisite hook for Add Existing User I have a custom post type created for new users when they are added to a multisite environment using the wpmu_new_user hook, but I noticed that it was only fired on new user creation and not when an existing user is added to a site. Is there a hook that gets fired when both new or existing users are added to a site?
There's one called `added_existing_user` that fires immediately after adding an existing user. Digging a little deeper, I find the function `add_user_to_blog()` is used by both `add_new_user_to_blog()` and `add_existing_user_to_blog()`, and has an action hook named `add_user_to_blog`. I'd look into using that last hook, if I wanted to ensure something happened when a user was added to a site, whether they were `_new_` or `_existing_`.
stackexchange-wordpress
{ "answer_score": 2, "question_score": 1, "tags": "multisite" }
How do I show the parent term on a custom taxonomy template (not the ID)? $term = get_term_by('slug', get_query_var('term'), get_query_var('taxonomy')); echo $term->name; echo $term->description; echo $term->parent; Name gives the name. Description gives the description. Parent gives the parent ID, not the term. How do I get the parent term (the word)?
Again use the `get_term_by()` function: $curr_taxonomy = get_query_var('taxonomy'); $term = get_term_by( 'slug', get_query_var('term'), $curr_taxonomy ); if ( $term !== FALSE && $term->parent > 0 ) $parent_term = get_term_by('id', (int) $term->parent, $curr_taxonomy ); else $parent_term = false;
stackexchange-wordpress
{ "answer_score": 0, "question_score": 0, "tags": "custom taxonomy" }
Custom post type's posts are not showing anywere but in xml sitemap I don't use any cache plugin. Custom post type's posts are only showing in xml sitemap but not showing in other places on the site, until I "open each new post url manually" or "use a third-party online tool to open each new post url manually" or "just open new post's source code url directly in incognito window". All these 3 things works and makes the post visible on site. I think its easy to fix this but I didn't found any solution to this. Any idea to fix this? Thanks
There are several tutorials like this one from WPBeginner that tell you how to create, then display a custom post type. You may need to create templates, and decide where and how they will display. You could list them as menu items, then use that menu in a sidebar using widgets. You could also use a plugin like Display Custom Post to list them in a more graphical way. Good luck!
stackexchange-wordpress
{ "answer_score": 1, "question_score": 0, "tags": "custom post types, plugins, functions, customization, theme development" }
unable to edit any page of my wordpress website I'm working on a website using ampps local server. when I try to edit any page this error occurs. Catchable fatal error: Object of class WP_Error could not be converted to string in /Applications/AMPPS/www/wp-includes/formatting.php on line 1111 This is the line on formatting.php line 1110 function wp_check_invalid_utf8( $string, $strip = false ) { line 1111 $string = (string) $string;
i think you should overwrite old file with NEW WORDPRESS file (formatting.php)
stackexchange-wordpress
{ "answer_score": 0, "question_score": 0, "tags": "fatal error" }
Wordpress json rest api displaying 10 categories only Wordpress rest api for categories is displaying 10 categories only. how can i get all list of categories in the api. please help me out of this. Thanks
This is the REST API Pagination: by default you'll get a page of 10 results and two headers in the results, X-WP-Total and X-WP-TotalPages, to tell you how many pages of results there are. You can request more results in one go by adding `?per_page=100` to the request, i.e. 100 is the maximum you can request at once. You should then check the `X-WP-TotalPages` header in the response and if it's more than 1 you need to repeat for further pages of results, i.e. etc. as appropriate.
stackexchange-wordpress
{ "answer_score": 0, "question_score": 0, "tags": "api" }
How to inherit custom javascript from parent to child pages? I have a function I wish to use in 10 different javascript files (each are used on a different webpage). I was hoping to avoid copying/pasting the function into every .js file. The pages all have the **same parent page**. Is there a way I can define this function once and call it from each page's .js file? Thank you in advance.
Just define the function in its own separate JS file, and load that file alongside the page-specific files. The "WordPress way" would be to register the script containing the shared function(s) and then set it as a dependency of the other scripts: wp_register_script( 'my-functions', get_theme_file_uri( 'js/functions.js' ) ); if ( is_page( 1 ) ) { wp_enqueue_script( 'my-page-1', get_theme_file_uri( 'js/page-1.js' ), [ 'my-functions' ] ); } if ( is_page( 2 ) ) { wp_enqueue_script( 'my-page-2', get_theme_file_uri( 'js/page-2.js' ), [ 'my-functions' ] ); } // etc.
stackexchange-wordpress
{ "answer_score": 1, "question_score": 0, "tags": "javascript" }
Choosing a default page tempate (Classic => Gutenberg) This code was working in the "Classic" era to set a default page template: /* Blank Page by default */ add_action('add_meta_boxes', 'blank_default_page_template', 1); function blank_default_page_template() { global $post; if ( 'page' == $post->post_type && 0 != count( get_page_templates( $post ) ) && get_option( 'page_for_posts' ) != $post->ID // Not the page for listing posts && '' == $post->page_template // Only when page_template is not set ) { $post->page_template = "page-template-blank.php"; } } Resulting in this behaviour: ![enter image description here]( **How to achieve the same in Gutenberg?** Currently, it looks like: ![enter image description here](
This is possible with javascript using the wp.data api. You can see this work in the console, by replacing the template name as needed: wp.data.dispatch('core/editor').editPost( {template: "templates/blank.php"} ) You would just need to run that at some point after the editor sidebar components have loaded in a check to see if the page template has been set yet.
stackexchange-wordpress
{ "answer_score": 0, "question_score": 1, "tags": "metabox, page template, block editor" }
Creating a child theme: How do I find the template name of the parent directory? I am trying to create a child theme for the Fitness Hub theme. I'm following this guide (< when it comes to part 2. it makes it clear I need to add a 'Template' header in the style.css (of the child theme), however there isn't a template name in the parent theme's style.css. So it's not clear to me what this template name should be. I used 'Template: fitnesshub', but this doesn't work, the child theme does not generate. I get the following error in my themes directory (on the browser): > The parent theme is missing. Please install the "fitnesshub" parent theme. When I install the parent theme (clicking the link) the same issue occurs. TIA.
As stated in the Theme handbook (< you need to use the parent theme dir name in the 'Template' header. In your case the template name would be. `Template: fitness-hub`
stackexchange-wordpress
{ "answer_score": 1, "question_score": 0, "tags": "child theme, parent theme" }
How to edit button permalink inside function.php using a child theme? I am using a WordPress theme called "business one page" and it has a slider with Learn-more button. Here is a demo of the theme Business-One-Page I am using a child theme and I want to change the permalink of the button by inserting code into the functions.php file. First, I tried to locate the slider code inside the home-page-template then I have opened all files and search for the btn(class="btn-more") without any results. I have found the .php file for all sections and pages except the slider. Is it possible that some parts of the code are not included? Is it possible to edit the permalink with coding? or do I have to create another button myself? I just wanted to change the permalink so it would not link to another page, instead link to content on the same page using (#content). Thanks
I recommend creating a child theme first so you can update later. Further, you can edit **/wp-content/themes/business-one-page/inc/extras.php** at line # 149 and replace with below code. <a class="btn-more" href="#content"><?php echo esc_html( $slider_readmore );?></a>
stackexchange-wordpress
{ "answer_score": 0, "question_score": 0, "tags": "php, permalinks, child theme, buttons" }
Mobile issue – website isn't properly detecting screen size my question concerns this website (currently on my staging server): < The theme is a child theme of a parent theme I created with Underscores and Bootstrap. I am getting some odd behavior when I view the website on my phone. See the screenshot below. ![Screenshot from Chrome Developer tools]( If I click another page in the menu, the website corrects itself and fits properly on the screen. However when I turn my phone to landscape, the full-size desktop version loads. Again, when I click another page in the menu, the website resizes itself to properly fit the screen. Any idea what is causing this?
Your primary menu container is set to `left: 5000px;` witch stretches the width of the page. You can find this style directive in _...themes/sunstone-bookkeeping/css/mobile.css on line 66_. @media screen and (max-width: 600px) .nav-menu { position: absolute; left: 5000px; } One way to fix this is to add the following styles to the parent element: .menu-menu-1-container { position: relative; overflow-x: hidden; } This solution shouldn't mess with other styles. The proper way of applying this kind of changes is described here: child themes. In the **style.css** file of your child theme you can safely add the solution that I proposed. Cheers!
stackexchange-wordpress
{ "answer_score": 0, "question_score": 1, "tags": "themes, child theme, mobile, responsive" }
How does a Genesis child theme understand that the Genesis theme is the parent theme? In most Genesis child themes, the following line of code exists: // Starts the engine. require_once get_template_directory() . '/lib/init.php'; I understand that this includes the init.php file from the lib directory within the Genesis parent theme folder. My question is simply - why does `get_template_directory()` return the Genesis parent folder, as opposed to the child theme folder? And how does it identify it if there are multiple parent themes possible?
I'm not experienced with Genesis, specifically, but I imagine its child themes work the same as child themes for any other theme. As documented, a child theme is created by adding a `Template:` line to the style.css header, which is the directory name of the parent theme: /* Theme Name: Genesis Child Theme Template: genesis */ By defining the "Template" for a theme, WordPress functions like `get_template_directory()` know to use that theme's directory for the path or URL.
stackexchange-wordpress
{ "answer_score": 1, "question_score": 0, "tags": "child theme, genesis theme framework" }
How to convert srcset links from https to http? After trying SSL and having some unfortunate problem with it, I decide to go back to HTTP. Everything seems find, by the `srcset` attribute of `<img>` tag is still https everywhere. This post Wordpress: srcset gets HTTP instead of HTTPS in all posts asks for the opposite direction, but still provides me guides to diagnose. However: 1. In `wp-includes > media.php`, I can find the `wp_calculate_image_srcset` method, but unable to find these two lines: $image_baseurl = _wp_upload_dir_baseurl(); $image_baseurl = trailingslashit( $image_baseurl ) . $dirname; 2. In `wp_options` table, both `home` and `siteurl` already have http values. I also delete all cache. Still no help. What else do I need to check? Here is my page: quảcầu.com.
@Ooker It's the Jetpack that is serving you the images on https. If you'd turn off the Photon add-on from Jetpack you should be able to get images served over http from your own server. Also if you turn off Photon, images won't be served from CDN anymore, so you might have to figure that out.
stackexchange-wordpress
{ "answer_score": 1, "question_score": 0, "tags": "database, https, images, http" }
How to change background image I am new to wordpress and although searched all over I cannot seem to find an answer for my question so any help would be appreciated: I have the following code: [vc_row row_type="parallax" content_width="grid" full_screen_section_height="yes" vertically_align_content_in_middle="yes" parallax_background_image="2407"] I need to change the `parallax_background_image="2407"` to another file. I have already uploaded the new file in the Media library but cannot find how to reflect the change. I assume I have to edit some css code but have no idea where to find the relevant code. FYI: there are several of those background images on the same page that I want to edit, if this is at all important. Any ideas?
This code isn't coming from Core, so you should search down where the shortcode comes from - a theme or a plugin. My guess is that "2407" might be the Post ID of a particular image. If that is true, then you can go into your Media Library and find the Post ID of the image you want, and paste that in instead of the 2407.
stackexchange-wordpress
{ "answer_score": 0, "question_score": 0, "tags": "images, css, custom background" }
Settings missing from the add new post page It has been a while since I used WordPress and it seems that lot have changed. It appears that I cannot see certain settings anymore, like set tags, set categories for a post, permalink and more. Can you help me finding them please ? Below you have a screenshot of what I see right now on the right side when I want to write an article. ![enter image description here](
You can enable it for screen options above if still not works you can install the classic editor plugin to go back to old wordpress admin editor
stackexchange-wordpress
{ "answer_score": 0, "question_score": 0, "tags": "posts" }
Create Wordpress Multisite Instance Programmatically Our CI process sets up everything from scratch, including WordPress, and our WordPress is a multisite instance. Adding a site after the Multisite functionality has been setup is easy to do programatically, but the initial setup seems to need to be done manually. Is there a way to setup the initial network tables without hitting install on the dashboard, maybe using WP-CLI or a build in method?
WP-CLI has a couple of commands to install Multisite (or convert a non-Multisite WP installation to Multisite): * `wp core multisite-install` * `wp core multisite-convert` Are either of those what you're looking for?
stackexchange-wordpress
{ "answer_score": 2, "question_score": 0, "tags": "multisite, wp cli" }
How to merge two .PO language files? I have a **.po** file that works with the theme and it contains **1259 characters** , and i translated many words in it. That been said, after the theme was updated i found out that the new .po files contains **1898 (460 more characters)**. So i would like to know if there is a safe and efficient way to merge these two files, that means keeping the integrity of manual translations i did + the new terms that were added by new version of the theme file. Can anyone tell me if there is a way to achieve this ? I'd appreciate it Thank you in advance
Since **.po** files are full text, you could first compare the files to see if the differences between the files occur at a specific place (is the addition only located at the end?), are the same keys used for different values?, ... to ensure that no data is being lost. To that purpose you could use: \- CLI tools such as diff or a program like Meld (which is based on diff) to get a visual aid when comparing the files. \- an IDE which provides file comparison possibilities (For example Atom with the add-on compare-files) You could try to merge the files together automatically by using the following CLI tool msgmerge.
stackexchange-wordpress
{ "answer_score": 0, "question_score": 1, "tags": "plugins, translation, plugin qtranslate" }
problem with size of debug.log file my debug.log file in wp-content size in above 4GB and have trouble with that. can I delete this file from the server? if delete debug.log file ، No problem with my site? Does everything correctly run in the server?
debug.log is exactly what it sounds - it’s just a file that contains log information for debugging purposes. You can easily delete it and without any fear. But... 1. Debugging should not be turned on on production site - it’s a security problem. 2. If your debug.log file is so big, then your site has many problems. This file contains PHP notices, warnings and errors. If everything works fine, then this file is almost empty. So the smart thing to do is: * download that file to your local machine, * delete it from server * check the content of that file and try to fix as much problems as you can * disable logging or at least make that file inaccessible.
stackexchange-wordpress
{ "answer_score": 1, "question_score": 0, "tags": "debug" }
Scheduled post delete - can't pass the cron arguments Thanks to everyone who takes a look. I've spent countless hours trying to make this work, but no matter what I tried it still doesn't work. Hopefully I'm missing something simple, but I'm stuck... Here's my code on the submit page where I add a new page and a cron job to delete it in the future: $seconds = time() + $_POST["days"] * 86400; wp_schedule_single_event($seconds, 'crondelete', $new_post_id ); And here's the relevant code in functions.php: add_action( 'crondelete', 'delete_page_in'); function delete_page_in($args) { wp_delete_post($args); } The cron part is working properly: ![enter image description here]( But it looks like the parameter isn't passed to the function, so once I run the cron job- nothing happens(the page won't delete).
Comparing your code to the Wordpress function **wp_schedule_single_event**, it appears you failed to indicate that parameters would be passed. Perhaps the following version of your code will work for you. add_action( 'crondelete', 'delete_page_in',10,1); wp_schedule_single_event($seconds, 'crondelete', array($new_post_id )); Notice the add_action now includes two extra parameters: 10=Priority, and 1=Accepted Arguments to be passed.
stackexchange-wordpress
{ "answer_score": 0, "question_score": 0, "tags": "functions, wp cron" }
Get a remote post ID via API given URL **Given you have a URL, how can you get the post ID of a post on a remote WordPress site?** As far as I can tell, you would have to: HTTP GET /wp-json/v2/posts And then look for your URL, but the problem is that this endpoint will only return 100 results by default. I don't want to have to download the ENTIRE content of a site just to find the post ID of a given URL. In V1 you could submit a query, but I think that's been depreciated. Any better ways to do this?
The Posts endpoint accepts a `slug` parameter when querying for posts, so if you can get the slug from the URL, then you can make request to `/wp-json/wp/v2/posts?slug=<slug>`. So if the URL is ` and you know the slug is `hello-world`, then for example in JavaScript, you can do something like: fetch( ' ) .then( res => res.json() ) .then( posts => console.log( posts[0].id ) ); Or you could create a custom endpoint.. if you've got control over the WordPress site. See this for more details.
stackexchange-wordpress
{ "answer_score": 3, "question_score": 0, "tags": "rest api, api, wp api, content restriction" }
Return value of get_permalink(0) and get_the_title(0) I'm new to wordpress and I'm following a tutorial right now but I don't understand wordpresses behaviour. I'm trying to change the title of a sidebar which lists the parentpage and it's childpages, this works fine but I don't understand why `$parentID = wp_get_post_parent_id(get_the_ID()); echo get_permalink($parentID);` works even on the parent page, I echoed the result on the parent page and it returns 0 since the parent page doesnt have a parent, so why does this still work? Why does `get_permalink(0)` get me to the parent page if I press the button on the parent page? It also gives me the Title even though it would be `get_the_title(0)`
If an ID is passed to `get_the_title()` or `get_permalink()`, they will use `get_post()` internally to get a copy of the full post object with that ID. But if `get_post()` is passed either nothing or a "falsy" value, like `0`, then it will return the current global `$post` object. In the context of your code this is _likely_ to be the current page. So: get_permalink( 0 ); Is equivalent to: get_permalink( get_the_ID() ); Which is equivalent to: get_permalink(); Because they are all referring to the current `global $post`.
stackexchange-wordpress
{ "answer_score": 2, "question_score": 0, "tags": "permalinks, child pages" }
Shortcode conflicts My plugin provide shortcodes like this: `[cfgeo return="city"]` \- returns city name `[cfgeo include="us"]Text only seen in the US country[/cfgeo]` \- returns this text only from the visitors in the US. If I place shortcodes in the content like this: <div>[cfgeo return="city"]</div> <div>[cfgeo include="us"]Text only seen in the US country[/cfgeo]</div> WordPress made error and parse it like this: <div>[cfgeo return="city"]</div><div>[cfgeo include="us"]Text only seen in the US country[/cfgeo]<div> That mean all between first chortcode and closed state of the shortcodes are parsed like one big shortcode. [cfgeo return="city"]EVERYTHING INSIDE[/cfgeo] And that made a error. How and do I can avoid this?
When you define your shortcode, you might try one of a couple "if" statements to fix this issue, until you have time to create separate shortcodes. function cfgeo_shortcode( $atts, $content = "" ) { if (!isset($content) || stristr($content,'cfgeo')!==FALSE){ // do short shortcode stuff here } else { // do 'Container' shortcode stuff here } return $output; } add_shortcode( 'cfgeo', 'cfgeo_shortcode' ); I would also recommend ... when you create your replacement shortcodes, you should not only create separate codes, you should also avoid parameters with keywords like "return" and "include" for their respective names. Good luck! Hope this was helpful.
stackexchange-wordpress
{ "answer_score": 1, "question_score": 0, "tags": "plugin development, shortcode, the content" }
How can i make wordpress blog title clickable and direct to the post itself How can i make wordpress blog event titles clickable and direct to their respective post itself? Thank you! <li id="post-<?php the_ID(); ?>" <?php post_class( 'stm_post_info' ); ?>> <?php if( get_the_title() ): ?> <h4 class="stripe_2"><?php the_title(); ?></h4> <?php endif; ?>
<li id="post-<?php the_ID(); ?>" <?php post_class( 'stm_post_info' ); ?>> <?php if( get_the_title() ): ?> <h4 class="stripe_2"><a href="<?php the_permalink() ?>" ><?php the_title(); ?></a></h4> <?php endif; ?> Please try this
stackexchange-wordpress
{ "answer_score": 0, "question_score": 0, "tags": "get the title" }
How to auto empty comment trash after X days I know how to programmatically delete comments that are X days old but they then go to the trash. How do I empty the comment trash every X days? function md_scheduled_delete_commentsmd_scheduled_delete_comments() { $comments = get_comments( array( 'post_type' => 'post', 'date_query' => array( 'before' => '3 days ago', ), ) ); if ( $comments ) { foreach ( $comments as $comment ) { wp_delete_comment( $comment ); } } } add_action( 'wp_scheduled_delete', 'md_scheduled_delete_comments' ); // You can test it immediately by adding following line: // add_action( 'wp_loaded', 'md_scheduled_delete_comments' );
When deleting a comment it's possible to use the second input argument: wp_delete_comment( $comment, $force_delete = true ) to delete it permanently and avoiding the trash bin. You could try to adjust your scheduled script accordingly. There's also the `EMPTY_TRASH_DAYS` constant, that's default set to empty the trash bin after 30 days, but it will affect comments, posts, pages and other post types.
stackexchange-wordpress
{ "answer_score": 1, "question_score": 1, "tags": "comments, automation, customization" }
Remove post content in RSS feed? I want to remove the post content that is displayed in the RSS feed. How can I do this? I just only want it to show a list of post titles and not the content
One way is to use filters like: add_filter( 'the_content_feed', '__return_empty_string' ); add_filter( 'the_excerpt_rss', '__return_empty_string' ); to remove the post excerpts and post contents from the feeds (atom, rss, rss2). But note that this will not remove the corresponding XML nodes from the feed, only their contents.
stackexchange-wordpress
{ "answer_score": 0, "question_score": 0, "tags": "rss" }
How to use get_the_title with text on the 'alt' of the_thumbnail array? I'm currently using `<?php the_post_thumbnail('250px', array('class'=>"review-siteshot", 'alt' => get_the_title() )); ?>` I know that `'alt' => "review"` will output review as all text. I'm trying to use `get_the_title()` along with "review" so that I get **title-text review** as my alt text for the thumbnail.
Like this: 'alt' => get_the_title(). ' review' So the full code would be: <?php the_post_thumbnail('250px', array('class'=>"review-siteshot", 'alt' => get_the_title(). ' review' )); ?>
stackexchange-wordpress
{ "answer_score": 2, "question_score": 0, "tags": "post thumbnails, get the title" }
Organizing uploaded Media in permalink-based folder structure? Wordpress seems to like storing files by year/month. This is nice, but not good enough for busy websites with loads of content. It'll be much nicer to have the folders reflect the exact same structure as the permalinks for them: /wp-content/uploads/custom-post-type/category/postname-1.jpg /wp-content/uploads/books/fiction/the-nun-1.jpg /wp-content/uploads/books/romance/the-italian-spring.jpg And so on. Is it possible to do this with some simple customized function in `functions.php`, or via some plugin? Thanks for any pointers.
There is another thread discussing this, with multiple answers. You might check to see if they address your desires. They offer some code, and an available plugin solution.
stackexchange-wordpress
{ "answer_score": 1, "question_score": 0, "tags": "uploads, media library" }
Order Posts in Custom Order I am trying to create a custom way to order my new custom post type. Here is what I am envisioning: * There would be a custom way to order posts in an entirely unique order for display (Number, automatic value, etc.) This would be so I could avoid needing to manually change a ton of publication dates on posts to get the right order. * If there was no number/automatic value/etc. entered then it would display based on when it was published at the end of the list. I am using CMB2 for the meta-data fields on my custom post type. Does anyone have any suggestions or ideas? I realize that this is a complicated problem, but I want to be able to order posts in a custom order that is not by author, date published, or title.
With `register_post_type()`, you can specify the `'page-attributes' => true` property, and you'll get the "menu order" metabox which you see on pages. With this you can custom order your items, where the default is always 0, which means they will always show, even if you don't set a value. You don't actually have to set the `page-attributes` attribute to use the the `menu_order` post property/column. You can set that value programmatically. To query with the custom ordering in place, you can use the `menu_order` property in your `WP_Query` args: <
stackexchange-wordpress
{ "answer_score": 1, "question_score": 0, "tags": "custom post types, query posts" }
Is it necessary to sanitize wp_set_password user input? I'm trying to add a password form to the WP registration form. See the code below. I was wondering if I need to sanitize this specific user input? (and if so how?) If I understand it correctly, WP has sanitizion built in for some things, and passwords may be one of them. Is that correct? Will WP sanitize it automatically before adding it to the database? add_action( 'register_new_user', 'registration_change_pass', 10, 99 ); function registration_change_pass( $user_id ) { if ( isset( $_POST['user_password'] ) ) { wp_set_password( $_POST['user_password'], $user_id ); } }
No, there is no need to sanitize passwords. You don't want to strip out or rewrite a value on users' set passwords. They will be hashed afterwards, so no need
stackexchange-wordpress
{ "answer_score": 1, "question_score": 1, "tags": "php, database, login, user registration, sanitization" }
Forgot password needs to redirect from wp-login to a custom page I'm new to WordPress. My question is, Now default user forgot password redirecting to `website/wp-login.php?action=lostpassword&redirect_to=http%3A%2F%2website.com%2Fuser-profile` But I have a custom page `/password-reset/`. So I refer some post and added below code in my theme function.php add_filter( 'lostpassword_url', 'my_lostpassword_url', 10, 0 ); function my_lostpassword_url() { return site_url('/password-reset/'); } But it's not working. So I added rewrite rule in .htaccess file - as first line RewriteRule ^wp-login.php?action=lostpassword$ website.com/password-reset/ [R=301,L] Both are not working. Any solution for this?
I see what you're trying to do, but it appears you only "ALMOST" followed the code example provided by the codex. Below is an annotated version of their sample code, substituting your desired URL: // You need the "10,2" in for WP to pass their parameters .. you can ignore them from that point forward. // 10 = Priority. Ensures it takes precedence, replacing the default. // 2 = Allows WP to pass two parameters. add_filter( 'lostpassword_url', 'my_lostpassword_url', 10, 2 ); function my_lostpassword_url( $lostpassword_url, $redirect ) { // I recommend using the WP method, although you could use your return value $redirect = '/password-reset/'; // Your url would also work. I just like the redirector... return site_url( '/lostpassword/?redirect_to=' . $redirect ); } Hope this helps!
stackexchange-wordpress
{ "answer_score": 0, "question_score": 1, "tags": "login, password" }
trying to add extra field using hooks I am trying to add an extra field on the backend menu of > Edit Subscription menu (SUMO Subscription (plugin) -> List of Subscription -> Edit Subscription) I am sending you a screenshot for where exactly I would like to add it. ![enter image description here]( do_action( 'sumosubscriptions_admin_after_general_details' , $post->ID ); // 10 is the priority, higher means executed first // 1 is number of arguments the function can accept add_action('sumosubscriptions_admin_after_general_details', 'custom_domain', 10, 1); function custom_domain($post) { // do something <input type="text" name="Domain" value="<?php echo $name;?>"> } I know it's possibly an easy one problem but I haven't succeed to find a solution. Thanks in advance for your help!
I'm not familiar with the subscription plugin you're using. But as you're attaching a custom function to a action hook, you should most likely echo or print the html you want to be displayed at that particular point. Like this, function custom_domain( $post_id ) { // if this is saved as post_meta then get it with get_post_meta( $post_id, 'some_meta_key', true ); $domain = 'someurl.com'; printf( '<input type="text" name="Domain" value="%s">', esc_url( $domain ) ); }
stackexchange-wordpress
{ "answer_score": 0, "question_score": 0, "tags": "custom field, actions, child theme" }
add_query_arg() and empty variables inside I have link: <a href="'.esc_url(add_query_arg(array('search' => $search, 'category' => $category, 'filter' => $filter), '/site')).'">Click</a> And some variables sometimes exist and sometimes don't, like $filter, which sometimes does not exist. Now I would like the variable does not exist, that it would not appear in the link, because the debugger displays the Notice "Undefined variable". How should it be coded correctly?
You can instantiate your array before-hand, optionally populate it, and pass it to the `add_query_arg()` function like so: $url_query_args = array(); if( isset( $search ) ) { $url_query_args['search'] = $search; } if( isset( $category ) ) { $url_query_args['category'] = $category; } if( isset( $filter ) ) { $url_query_args['filter'] = $filter; } esc_url( add_query_arg( $url_query_args, '/site' ) ); Or you could loop through an array of possible query args: $url_query_args = array(); $possible_args = array( 'search', 'category', 'filter', ); foreach( $possible_args as $arg ) { if( ! isset( ${$arg} ) ) { continue; } $url_query_args[ $arg ] = ${$arg}; } esc_url( add_query_arg( $url_query_args, '/site' ) );
stackexchange-wordpress
{ "answer_score": 1, "question_score": 1, "tags": "query, links" }
Will 'private' status prevent Woocommerce products to be indexed by search engines? I'm currently disabling some Woocommerce product from my site and for this, I set them as `private`. I'd like to know if 'private' will **also** set the `no index` meta as true?
If you are using the default Wordpress method of marking a post/page private, NO. This only prevents that post/page content from being viewable. Google (and other search bots) will not find private pages. Only logged in blog Editors and Administrators can see Private pages. So, while Wordpress will not add the meta to block bots, your private pages still will be invisible to Search Engines.
stackexchange-wordpress
{ "answer_score": 0, "question_score": 0, "tags": "woocommerce offtopic, private, search engines, noindex" }