INSTRUCTION
stringlengths
11
999
RESPONSE
stringlengths
0
999
SOURCE
stringlengths
16
38
METADATA
dict
Rewrite Point Doesn't Work on Custom Taxonomy I have a custom taxonomy (in a custom plugin) for which I have included the argument 'ep_mask' => 'EP_CATEGORIES' for rewrite (this uses WDS' Taxonomy_Core): 'args' => array( 'hierarchical' => false, 'show_admin_column' => false, 'rewrite' => array( 'slug' => 'sermon-series', 'with_front' => false, 'ep_mask' => 'EP_CATEGORIES', ), I then have in my theme's functions.php file the following instruction to create a rewrite endpoint: function lqd_app_view_rewrite_endpoint() { add_rewrite_endpoint( 'app-view', EP_ALL); } add_action( 'init', 'lqd_app_view_rewrite_endpoint' ); When I view say: < This works perfectly. However, when I try to use it on a custom taxonomy, I get a page not found error: < Any thoughts on what I'm doing wrong? Thanks!
One thing I noticed is that you're defining EP_CATEGORIES as a _string_ , however it's actually a _constant_ (defined in WordPress Core). So for example you should define your `ep_mask` like so (without quotes): 'ep_mask' => EP_CATEGORIES, You may need to flush the rewrite rules after making this change.
stackexchange-wordpress
{ "answer_score": 1, "question_score": 1, "tags": "plugin development, custom taxonomy, url rewriting" }
Automatically check the option "Enable stock management at product level" on product creation We have a peculiar WooCommerce setup where each product is only sold once. So we set each product to have 1 stock on creation automatically. Using stock management feature in WooCommerce requires an option: "Enable stock management at product level" with a checkbox to be "checked" Is there a function or anything I can use to make this box "checked automatically" upon product creation? Thanks for any help!
To set default values of a new post, you can try this code : $postType = "product"; add_action("save_post_" . $postType, function ($post_ID, \WP_Post $post, $update) { if (!$update) { // default values for new products update_post_meta($post->ID, "_manage_stock", "yes"); update_post_meta($post->ID, "_stock", 1); return; } // here, operations for updated products }, 10, 3);
stackexchange-wordpress
{ "answer_score": 4, "question_score": 2, "tags": "php, woocommerce offtopic" }
Catchable fatal error: Object of class WP_Error could not be converted to string in i need help with this: > Catchable fatal error: Object of class WP_Error could not be converted to string in /home/.../public_html/wp-content/themes/toroplay 2.1.2/inc/single-series.php on line 156 its this line: 153-156 : $array_directors = array(); $term_list_directors = wp_get_post_terms($post->ID, 'directors_tv', array("fields" => "all")); if(!is_wp_error($term_list_directors) and !empty($term_list_directors)){ foreach($term_list_directors as $director_single) { $array_directors[]='<a href="'.get_term_link($director_single->term_id, 'directors').'">'.$director_single->name.'</a>'; }
You get the terms of `directors_tv` taxonomy, but try to get the next link in the context of `directors` taxonomy. You probably should use `directors_tv` in both places or rethink your DB structure as you can not use the same term id in the context of different taxonomies.
stackexchange-wordpress
{ "answer_score": 0, "question_score": 0, "tags": "fatal error" }
To Disable Wordpress Rest API or Not To Disable? I have my blog self hosted running WordPress and I Do NOT need the Wp-Rest API. But as it turns out disabling it is causing to Contact Form 7 To not work. Contact form 7 simply shows the spinning circle infinitely. As I read on wpbeginner (link here) that disabling will boost security. So my question is if I leave it enabled, which I intend to do. What safety precautions should I take? Thanks
You personally might not need or rely on the WP REST API, but clearly Contact Form 7 does. And so does WordPress core. Especially future versions (think Gutenberg) will heavily rely on the REST API and won‘t work without it. There might be plugins that disable the API, but that‘s at your own risk and certainly doesn‘t make your site suddenly secure. It might decrease the possible attack surface, sure, but at the cost of breaking all parts that rely on the API. tl;dr: There‘s no point in disabling the WordPress REST API.
stackexchange-wordpress
{ "answer_score": 8, "question_score": 5, "tags": "plugins, rest api, plugin contact form 7" }
Gravatar images are not fetched in Ultimate Member plugin Is it not possible to use Gravatar images in Ultimate Member Plugin? Or is it an issue that its not working? Under users tab (Ultimate Member -> Settings -> Users) "Use Gravatars" is enabled, still it shows empty/default gravatar than user's gravatar avatar/image.
Based on my testing and information from the developers, Gravatars won't appear until you use the _Gravatar Transfer_ feature to transfer the images to the local profile. That feature can be enabled from _Ultimate Member_ > _Settings_ > _Extensions_. Once it's activated, you can transfer the Gravatars from _Ultimate Member_ > _Gravatar Transfer_. You'll need to run that feature periodically in order to keep the Gravatars up to date.
stackexchange-wordpress
{ "answer_score": 2, "question_score": 1, "tags": "plugins" }
Why insert post function do not set the modified author without administrator panel? I am have a front-end new post and edit post forms. * I'll using the `<?php wp_insert_post( $post ); ?>` Everything is all right here. If any **editor** or **admin** modified any author posts on front-end: `<?php the_modified_author(); ?>` not working. But modified on `/wp-admin` administrator panel working it. > I want to update `<?php the_modified_author(); ?>` on my function! But how?
`the_modified_author()` displays the name of the user whose ID has been stored in the `_edit_last` post meta field. If you want to update the ID after another user has updated the post, you can use something like `update_post_meta( $post_ID, '_edit_last', get_current_user_id() );`. Then the new user's name will be displayed when using `the_modified_author()`. Replace `get_current_user_id()` with a custom user ID if it's not the current user who's updating the post.
stackexchange-wordpress
{ "answer_score": 2, "question_score": 0, "tags": "front end, wp insert post" }
How Can I Change a Taxonomy URL Based On The Originating URL? I previously wrote a question about rewriting a URL based on an originating URL and Milo provided me with a working answer for pages/posts. But now I am trying to do a taxonomy rewrite and the same functionality seems to break things. Here is my code: function lqd_series_link( $term_id, $taxonomy ) { if ( $taxonomy == 'gc-sermon-series' && isset( $wp_query->query_vars['app-view'] ) ) { return $taxonomy; // I've also tried $link } return $taxonomy; } add_filter( 'term_link', 'lqd_series_link' ); What is strangest is what this results in. So if I do the code as Milo instructed on the question linked above I end up with a URL for pages like: < But when I use the above code I end up with the same exact thing: < Thoughts?
The `term_link` filter has a different signature for its callback function than the `page_link` filter, meaning the arguments in your callback are different. (Also note you'll need to explicitly set the argument number when you call `add_filter` because by default `add_filter` will only setup 1 argument. For example: add_filter( 'term_link', 'lqd_series_link', 10, 3 ); // Where 3 is the number of arguments for your callback function Then in your callback: function lqd_series_link( $url, $term, $taxonomy ) { global $wp_query; if ( $taxonomy == 'gc-sermon-series' && isset( $wp_query->query_vars['app-view'] ) ) { return $url . 'app-view/'; } return $url; }
stackexchange-wordpress
{ "answer_score": 1, "question_score": 1, "tags": "custom taxonomy, filters, url rewriting, terms" }
Form submissions that require users ID# I'm new to asking questions here, so any help would be appreciated. I'm managing a Wordpress website for an organization that is going to have an upcoming election of board members and they'd like to do it online using a form. They currently use Ninja Forms. In order to verify each form submission they want to see if it is possible to only accept forms after the person enters a serial number that will be assigned to them, or possibly the ID# that Wordpress automatically assigns to users. Any thoughts on accomplishing this? Or the best place to track down a developer to help accomplish this. Thank you in advance. AJ
If you don't want to touch code, you could create a page whose content only logged-in users can see. That way only valid users can see the form. You'd want to look for a content restriction / membership plugin to handle the protection of that page. You can set a field - perhaps their email address - to only accept unique submissions, so if someone tried to vote twice, Ninja Forms would prevent them from even submitting a duplicate. If you want to touch code, you could register a hidden field in your form (see < but instead of including user IP you'd use `get_current_user_id()` to capture their auto-generated WP ID). You would then also want to create a child theme and apply a template to that specific page to hide the form if the current user is not logged in.
stackexchange-wordpress
{ "answer_score": 0, "question_score": 0, "tags": "forms, plugin ninja forms" }
wp-admin pages return ERR_EMPTY_RESPONSE update-core.php, update.php, and options-general.php no longer work. index.php, profile.php, plugins.php, upload.php, etc all still seem to work I have tried deactivating every plugin and reverting my theme to the default, but that didn't work. I downloaded a fresh copy of 4.9.2, and used my current wp-config.php with it, but the pages still did not work. I can activate and deactivate plugins, change the appearance of pages and content, but I cannot update or delete any plugins. WP_DEBUG and WP_DEBUG_LOG didn't reveal anything. What steps can I take to troubleshoot this? Is something in the SQL database corrupted?
< After a lot of digging and following segfaults in strace and parsing out apache core dumps (and enlisting some outside help from a much more knowledgeable Linux guy) I dug this up on Wordpress's site. The short answer to the problem is that there is an issue with PHP5 and libssh2 that was introduced in an update a few months ago. There is no actual fix for it, but it can be effectively worked around by installing this plugin: < It worked like a charm for me; all my users can log in normally and I can once again update plugins and WP Core through the GUI. Hope this works for you, and others!
stackexchange-wordpress
{ "answer_score": 4, "question_score": 4, "tags": "wp admin, updates, options" }
How to append something before final </ul> tag in walker class? Here is the real picture I want to produce. <ul> <li> <ul> <li> </li> <li> </li> ###NOT HERE ### </ul> </Ii> ###I want to add some html here ### </ul> I am trying as follows: public function end_lvl( &$output, $depth = 0, $args = array() ) { if ( isset( $args->item_spacing ) && 'discard' === $args->item_spacing ) { $t = ''; $n = ''; } else { $t = "\t"; $n = "\n"; } $indent = str_repeat( $t, $depth ); $output .= "$indent".get_search_form(false)."</ul>{$n}"; } But it appended the search box at the end of every sub menu(###NOT HERE ### section). How can I achieve the desired output. Any idea?
I apply this trick to filter the menu: add_filter('wp_nav_menu_items','add_search_box_to_menu', 10, 2); function add_search_box_to_menu( $items, $args ) { if( $args->theme_location == 'primary' ) return $items."<li class='menu-header-search'><form action=' id='searchform' method='get'><input type='text' name='s' id='s' placeholder='Search'></form></li>"; return $items; }
stackexchange-wordpress
{ "answer_score": 0, "question_score": 0, "tags": "walker" }
How can I append and prepend something to all post hyperlinks without using ::before or ::after? PHP hook solution? I have links on my website that use the before and after pseudo elements to style them. I would like to append and prepend brackets to all links. Like this: > This is an example of a paragraph in a post. It would look like this but when it comes to a hyperlink it would look like [[ this ]]( You see how I put a bracket before and after the link? I want to do that, but I can't using the before after elements because they're already being used for something else. surely there's a way to do this in functions.php or something right? I know that Advanced Custom Fields has a way to append any custom field you make, so it seems like it shouldn't be that hard.
Doing this with a WordPress hook would be difficult to do reliably. But it's straightforward with jQuery and some CSS. jQuery('a').wrap('<div class="brackets"/>'); .brackets:before { content: "\005B"; } .brackets:after { content: "\005D"; }
stackexchange-wordpress
{ "answer_score": 1, "question_score": -1, "tags": "functions, css, hooks, links" }
How do I add a "Cancel" button on the subscriptions listing page I have managed to find the action where I can add the code for the button, but the problem is that I can't find how to create a cancel link anywhere. Does anyone know how to do it? So here is the code I got so far: function woocommerce_cancel_button() { ?> <a href="#" class="button view"><?php echo esc_html_x( 'Cancel', 'cancel a subscription', 'woocommerce-subscriptions' ); ?></a> <?php } add_action( 'woocommerce_my_subscriptions_actions', 'woocommerce_cancel_button', 10 );
I was looking for the same thing but couldn't find it anywhere so I tried to do it myself. Here's my code by the way. Hope this helps. function addCancelButton($subscription) { $actions = wcs_get_all_user_actions_for_subscription( $subscription, get_current_user_id() ); if(!empty($actions)){ foreach ( $actions as $key => $action ){ if(strtolower($action['name']) == "cancel"){ $cancelLink = esc_url( $action['url'] ); echo "<a href='$cancelLink' class='button cancel'>".$action['name']."</a>"; } } } } add_action( 'woocommerce_my_subscriptions_actions', 'addCancelButton', 10 );
stackexchange-wordpress
{ "answer_score": 4, "question_score": 2, "tags": "woocommerce offtopic, subscription" }
WooCommerce add custom product_type_option I added custom product_type_option like this ![enter image description here]( by filter product_type_option hook like this function rpf_add_wild_card_product_type_option($type_options) { $checked = 'no'; $type_options['wild_card'] = array( 'id' => '_wild_card', 'wrapper_class' => 'show_if_simple', 'label' => __('Wild Card', 'woocommerce'), 'description' => __('Please check if this product is wild card', 'woocommerce'), 'default' => $checked, ); return $type_options; } add_filter('product_type_option', 'rpf_add_wild_card_product_type_option', 100, 1); But, WooCommerce never save Wild Card Field! I want WooCommerce treat my wild card product type option like Virtual,Downloadable Field. What should I do in this case?
Your code only creates the checkbox, you need also to save the value like that add_filter("product_type_options", function ($product_type_options) { $product_type_options["wildcard"] = [ "id" => "_wildcard", "wrapper_class" => "show_if_simple", "label" => "Wildcard", "description" => "Description", "default" => "no", ]; return $product_type_options; }); add_action("save_post_product", function ($post_ID, $product, $update) { update_post_meta( $product->ID , "_wildcard" , isset($_POST["_wildcard"]) ? "yes" : "no" ); }, 10, 3);
stackexchange-wordpress
{ "answer_score": 5, "question_score": -1, "tags": "woocommerce offtopic" }
Can't write pdf file to upload directory using FPDF PHP Warning: file_put_contents( failed to open stream: HTTP wrapper does not support writeable connections in /home/t21jv08zz60b/public_html/wp-content/plugins/mortgage/fpdf181/fpdf.php on line 1023 [27-Jan-2018 11:24:20 UTC] PHP Fatal error: Uncaught Exception: FPDF error: Unable to create output file: in My Code: $filename=$upload_path.'deals/deal'.$page->id.'.pdf'; ob_clean(); $pdf->Output('F',$filename); FPDF: if(!file_put_contents($name,$this->buffer)) $this->Error('Unable to create output file: '.$name); break;
`$name` apparently contains a URL. That won't work. Set it to a local path, as you did with `$filename`: $upload_dir = wp_upload_dir(); $filename = $upload_dir["basedir"] . '/deals/deal' . $page->id . '.pdf';
stackexchange-wordpress
{ "answer_score": 3, "question_score": 2, "tags": "uploads, filesystem" }
Author functions don’t work in customizer’s selective refresh Is there a bug or something that prevents post author’s functions not to work in customizer selective refresh callback? It renders fine on initial page load, but author functions don't show after the refresh. Other functions seems to work fine. Here is my demo callback function for selective refresh: function refresh_callback() { echo get_author_meta('ID'); // isn’t rendered after refresh / setting change echo get_the_title(); // is rendered fine after refresh / setting change }
The selective refresh request doesn't get the whole regular WordPress request context. That is why on initial load (regular request) it works, while on AJAX partial refresh it doesn't. In your case, the global `$authordata` is not set and `get_the_author_meta()` is relying on it when no user is explicitly provided. You will need to do a little bit of work yourself: function refresh_callback() { // First get the current post $current_post = get_post(); // Test if we actually have a post content (we might be in an archive context) if ( ! empty( $current_post ) ) { echo get_the_author_meta('ID', $current_post->post_author ); echo get_the_title( $current_post ); } }
stackexchange-wordpress
{ "answer_score": 1, "question_score": 2, "tags": "theme customizer" }
Locked out of WordPress admin area I cant login into my website even when I input my correct login credentials. I tried to reset my password, but I did not receive the email. What can I do? Please help. I have the access to cPanel.
Since you have access to cPanel, you can reset your password via phpMyAdmin. Here is a tutorial. How to Reset a WordPress Password from phpMyAdmin PS: There are many questions about this issue in Wordpress StackExchange, so please take a look at them.
stackexchange-wordpress
{ "answer_score": 0, "question_score": 0, "tags": "login, password" }
How to delete field using WPDB? How can I delete a field in my database under the posts table? For example in my `posts` table where the ID is 800 I would like to delete the a field under the column `product_rank`. Any help will be appreciated.
You can't "delete" a field in MySQL, this only works for complete rows. However, you can unset values, meaning setting them to their original state, usually `NULL` or an empty string. $wpdb->update($wpdb->posts, array( 'product_rank' => NULL ), array( 'ID' => $post_id ));
stackexchange-wordpress
{ "answer_score": 2, "question_score": -1, "tags": "database, wpdb" }
How to change path for default WordPress blog posts? My site has a few custom post types each with their own base slugs (e.g. /workouts/, /trainers/, etc). I would like to give the **default** WordPress blog posts their own base slug (e.g. /blog/) without affecting the base slug of the other custom post types. Whenever I change the permalink structure in Settings->Permalinks to "/blog/%postname%" it affects **all** posts, so my other paths become "/blog/workouts/", "/blog/trainers/", etc. Is there a way to move only the base slug for the default WordPress blog posts? So I would have the archive on /blog/ and the posts like /blog/some-post-title/ Is the only way to create yet another custom post type?
For this, you need to alter the way you register your custom post type to not use the "front" of your URL structure (like "blog") for the URLs of that custom post type. You need to add this to your arguments array for the `register_post_type()` call: 'rewrite' => array( 'with_front' => false, ),
stackexchange-wordpress
{ "answer_score": 2, "question_score": 0, "tags": "custom post types, permalinks" }
Wordpress single sign on using cookies with shared user role functionality between more than 2 wordpress subdomains I have more than 2 wordpress subdomains. Before this, I tried using wordpress multisite, but my hosting doesn't has wildcard subdomain. I want to manually change subdomain directory to be appointed on public html, but my hosting doesn't has that functionality too. So my last option is to make single sign on using cookies. I have created custom user table anda custom user meta, also created same cookies path between 2 of my wordpress sites, following this tutorial: < I have success, but there is a problem. When I log in into second wordpress, I doesn't have a same role as my first site. Do you guys have a solution so I can create sso with shared user role for 2 or more wordpress subdomains? Thanks.
did you try to use a plugin instead, < have a look at this and this one < hope this might help
stackexchange-wordpress
{ "answer_score": 0, "question_score": 0, "tags": "multisite, user roles" }
Stop unwanted WP redirection to new url I had a custom type post, for which I changed the url. I have refreshed permalinks and cleared site and browser cache. The old url now redirects to the new url automatically. Possibly because the post ID is the same (?). Is it possible the stop the old url to direct to the new url?
WordPress uses a function called `wp_old_slug_redirect()` to find out if you're looking for a post whose slug was recently changed and redirect you to its new home. If you want to prevent this behaviour for this specific post, delete the `_wp_old_slug` post meta entry from the database for that post. If you want to prevent this behaviour for _all_ posts, prevent the function from being used at all: remove_action( 'template_redirect', 'wp_old_slug_redirect' );
stackexchange-wordpress
{ "answer_score": 6, "question_score": 3, "tags": "redirect, urls, wp redirect" }
What is the diferences between pure Wordpress theme and Woocommerce theme? I've made some WP simple sites, so I already know how to create a WP theme, but now I want to create simple e-commerce, with woocommerce, so, I need to know how to create woocommerce themes? Is there much diferences from a simple WP theme? And can you provide some links and directions where I can study it? Thanks in advance.
There are no "WooCommerce themes", only WordPress themes that eventually offer CSS styling for WooCommerce pages and layout elements, and, maybe, customize them by overwriting the WooCommerce templates. This is a good place to start: < Also, take a look at the "official" WooCommerce theme right from the creators: < Apart from these, the internet is brimming with resources: <
stackexchange-wordpress
{ "answer_score": 2, "question_score": 0, "tags": "theme development, woocommerce offtopic" }
Function added using `add_action()` not being called I'm a Javascript developer and I am very new to PHP/Wordpress. So just like what I saw from samples around the internet I wrote my `functions.php` script to add my custom css file like this: **functions.php** <?php echo '<h1>CASH ME OUTSIDE</h1>'; add_action('wp_enqueue_scripts', 'theme_styles'); function theme_styles() { echo '<h1>CASH ME INSIDE</h1>'; wp_enqueue_style('theme_styles', get_template_directory_uri() . '/foo.css'); } ?> To check if the `functions.php` is being called I printed `<h1>CASH ME OUTSIDE</h1>` and it did appear. How ever the echo inside the function `theme_styles()` is not being printed which leads me to the conclusion that the function is not being called.
A `echo` in functions.php, `wp_enqueue_scripts` or any other non-template file probably breaks the output due to a fatal error because of headers already sent. `echo` is not a proper way to debug. Delete the echo statements and check the HTML of the page, your css should be there. To debug, use error logs. Other than that, your code seems correct; be sure to include `wp_head()` and `wp_footer()` in your theme. Those functions are needed to print the enqueued scripts and styles; then just do this: add_action('wp_enqueue_scripts', 'theme_styles'); function theme_styles() { // You can use error_log, a native PHP function, // or any other custom log function if( WP_DEBUG ) { error_log('some debug information'); } wp_enqueue_style('theme_styles', get_template_directory_uri() . '/foo.css'); }
stackexchange-wordpress
{ "answer_score": 4, "question_score": 0, "tags": "functions, actions" }
How to "remove" file from parent theme I am having an issue with a theme I am using. The parent theme has created a woocommerce.php file. When this file exists, it takes precedence over the woocommerce hooks, and it causes issues when I want to use hooks to add content before the woocommerce content. Is it possible for a child theme to declare that the woocommerce.php file from parent should be ignored ?
The child theme could just delete the parent theme file if it exists (via child theme functions.php). eg. $template = get_template_directory().'/woocommerce.php'; if (file_exists($template)) {unlink($template);} That would continue to override it if it came to exist again (ie. after a parent theme update.) If you aren't going to update the parent theme just delete it's `woocommerce.php` If it's a file other than the WooCommerce files and just another file in the parent theme, copy it into the child theme and remove it's content just leave the `<?php ?>` tags if the content of the file is not needed.
stackexchange-wordpress
{ "answer_score": 0, "question_score": 0, "tags": "child theme, parent theme" }
Beginner question: Accessing functions.php through admin web interface in order to import custom post types? Is it possible to access the functions.php file just by using the admin web interface? I'm trying to access previously created (manually coded) custom post types and I'm having to jump through a lot of hoops because I can't access the code in the functions.php file. I've looked through a number of help pages, but the steps suggested always seem to involve the functions.php file (which I can't access) or the use of import/export tools from the plugin that created the custom post types in the first place (and no plugin was used as far as I can tell). This seems like a really basic issue, but I can't figure it out for the life of me. Any help would be greatly appreciated!
It is sometimes possible to edit theme files, including `functions.php`, inside wp-admin. Many hosts and devs disable this feature since it can cause security issues as well as allow you to break the site. So if you can access the file via FTP, that's generally the recommended method. If you don't see "Appearance > Editor" in your admin menu, either you don't have permission to edit files (a role/capability issue), or else the feature has been disabled. You can check your `wp-config.php` file and see if it has been disabled here - if it has, you'll see `define('DISALLOW_FILE_EDIT', true);`. Though if you can access wp-config, you should also be able to access theme files. :) If this is not the case, check with your host to see whether they have disabled file editing in the admin area and to find out whether they can enable it for your site.
stackexchange-wordpress
{ "answer_score": 3, "question_score": 2, "tags": "custom post types, functions, import" }
Which Template Page Should I Use? I have created several custom post types (for example: FAQs, products and case studies) and registered a global custom taxonomy for use across all CPTs. In my case this taxonomy is called _audiences_. These are listed as consumers, architects and merchants. In this example I'll use FAQs in the Merchants taxonomy. * * * I'm struggling to figure out how to filter the FAQs to show for a specific audience. My `archive-faqs.php` lists all FAQs regardless of audience type. I want to be able to show all the FAQs tagged as merchant. What are my options for this? * Do I create a custom `page.php` template and create a custom loop for it? * Do I some how amend my `archive-faqs.php` to grab a query string? * Is there a better way for me to achieve this goal?
you could always make a custom wp_query and put it in a template-custom.php. $the_query = new WP_Query( array( 'post_type' => 'faqs', 'tax_query' => array( array ( 'taxonomy' => 'audiences', 'field' => 'slug', 'terms' => 'merchants', ) ), ) ); while ( $the_query->have_posts() ) : $the_query->the_post(); // Show Posts ... the_title(); endwhile; /* Restore original Post Data */ wp_reset_postdata();
stackexchange-wordpress
{ "answer_score": 1, "question_score": 0, "tags": "custom post types, custom taxonomy, menus, archive template" }
WP REST api.wordpress.org discovery I have no problem doing REST discovery of routes and endpoints on **wordpress.org** : I'm trying to do the same for **api.wordpress.org** with no success. The following: redirects me to ` which is **REST API Handbook**. Does anyone know, how to do REST discovery on **api.wordpress.org**? Maybe it's not available.
< is a custom PHP API and is not running WordPress. Thus, there's no WP REST API that you could use for discovery. That URL has nothing to do with the REST API in core except for that redirect to the handbook. Unfortunately not all of the API endpoints are documented or either open sourced, as you can see when browsing SVN or looking at the plugins API code directly. If you have any questions about stuff that's currently in development there, you should really ask in the #meta Slack channel instead of here or raise an issue on Meta Trac. Also, since it's really in development and not intended for public use just yet, I'd highly recommend you to simply stick to the 1.0 or 1.1 version of the API.
stackexchange-wordpress
{ "answer_score": 3, "question_score": 1, "tags": "rest api" }
Can I show all the template files that are being used on my site? I have a legacy theme that has a lot of page template files. My site is too big to go through each page one by one to check it's template. Is there any way (either through adding a column to the pages list in the the backend, or in the database directly) to see which templates files are being used and determine which are surplus?
this would add a column with the page template file name into the 'Pages' in the dashboard: // ONLY WORDPRESS DEFAULT PAGES add_filter('manage_page_posts_columns', 'custom_admin_columns_head', 10); add_action('manage_page_posts_custom_column', 'custom_admin_columns_content', 10, 2); // ADD NEW COLUMN function custom_admin_columns_head($defaults) { $defaults['page_template_file'] = 'Page Template File'; return $defaults; } // SHOW THE PAGE TEMPLATE FILE NAME function custom_admin_columns_content($column_name, $post_ID) { if ($column_name == 'page_template_file') { $page_template_file = get_post_meta( $post_ID, '_wp_page_template', true ); echo ($page_template_file ? $page_template_file : '-'); } } based on: < <
stackexchange-wordpress
{ "answer_score": 1, "question_score": 1, "tags": "theme development, page template" }
I want to add specific word on Title bar how to do this I want to add "Buy" word in Just Title tab not in post Title Which show in image how can do this can some one help on it?? ![I want to add Buy word in before title]( ![Not here](
You may try Yoast plugin to customize meta title, description etc - ![Here is the screenshot](
stackexchange-wordpress
{ "answer_score": 0, "question_score": -1, "tags": "custom post types" }
display text on the same line No matter what I do (stripping html tags or not) the following statement displays the result on 2 lines rather than one: $text = sprintf( '<p>%1$s %2$s</p>', wp_filter_nohtml_kses( the_author_meta('user_firstname') ), __( 'hasn\'t published any articles yet.', 'monochrome-pro' ) ); Any idea why this is happening?
Note that `the_author_meta()` doesn't _return_ the meta value, but _echoes_ it. That's why the name is suddenly outside the `<p>` element. Use `get_the_author_meta()` if you need to return (and do something with) the field, rather than just display it. I'd highly recommend you to change your use usage of `__()` too, because that is not useful for translators as it's missing the name as context. /* translators: %s: user's first name */ $text = sprintf( __( "%s hasn't published any articles yet.", 'monochrome-pro' ), esc_html( get_the_author_meta( 'user_firstname' ) ) ); echo '<p>' . $text . '</p>'; Note: if you don't trust your translations, you should use `esc_html()` on `$text` instead of the user meta. As mentioned in the comments, using KSES functions is a bit overkill. If you want to get rid of any HTML tags (vs. just escaping them) I'd use `wp_strip_all_tags()`.
stackexchange-wordpress
{ "answer_score": 1, "question_score": 0, "tags": "html, genesis theme framework" }
Will WordPress Auto Update work on a site with Basic Authentication enabled? I'm trying to setup WordPress Auto Patching on a site with Basic Authentication enabled (ie via .htaccess). I've setup a proper cron job to trigger the Auto Update process (with the Basic Authentication credentials in the URL so as to avoid this being blocked), however the Auto Update still doesn't seem to work. Is the presence of Basic Authentication likely to be the problem here? Thanks!
Yes, it will work. For Updates, WP reaches out to the update servers, there is no incoming request that is necessary. Your WP doesn't even have to be publicly reachable at all, you can have it behind a NAT router and (auto-) updates will still work just fine.
stackexchange-wordpress
{ "answer_score": 0, "question_score": 0, "tags": "automatic updates" }
How to display custom WP menus? My task is to create local menu which will be displayed if specific page is open (checking page). For now I would like to display my custom menu. I am creating custom menu from Appeerance-Menus. After theat in functions.php I am doing the following: function register_my_menus() { register_nav_menus( array( 'explore_menu' => __( 'Explore Menu' ), ) ); } add_action( 'init', 'register_my_menus' ); AFter that I mark the check box Explore menu in the dashboard, such that my menu is marked as Explore menu. In my page.php I am adding this: <div id="primary" class="content-area"> <?php wp_nav_menu( array( 'theme_location' => 'explore_menu' ) ); ?> I expect to see the menu I created, but I dont see it. WHat could be the problem???
I had the same problem some time ago and solved it by adding my custom menu in my custom theme `header.php` (inside tag) instead of `page.php`. wp_nav_menu( array( 'theme_location' => 'my-custom-menu', 'container_class' => 'custom-menu-class' ) ); Here you can find a brief explanation about how to create and insert your custom menu Hope you can solve it!
stackexchange-wordpress
{ "answer_score": 0, "question_score": 1, "tags": "custom post types, php, menus" }
Is it possible to add/tick a category to a post when it is created? I thought the category "Uncategorized" is automatically added to every post, but I have found it only does when no other category has been selected. Is there any way to have it added every time automatically, whatever the case?
You can add a category on post creation with this code : $postType = "post"; add_action("save_post_" . $postType, function ($post_ID, \WP_Post $post, $update) { if (!$update) { // default values for new posts $post_categories = [get_option("default_category")]; wp_set_post_terms( $post->ID , $post_categories , "category" ); return; } // here, operations for updated posts }, 10, 3);
stackexchange-wordpress
{ "answer_score": 3, "question_score": 0, "tags": "posts, categories" }
Woocommerce categories displayed on every category and shopping page Since we updated to the latest version of woocommerce today we've been having a problem. On every category page and shop page it displays all of the main categories (not the sub categories) we have on the website. We've tried putting the display type on categories from default to all the other options, but not one seems to be doing the trick. Instead, it adds the subcategories on top of the main categories on the shopping page. Is anyone else having the same problem or know how to fix this?
Ok, problem solved be installing an older Woocommerce version (3.2.6). All the wrong categories are gone now and everything is back as it supposed to be.
stackexchange-wordpress
{ "answer_score": 0, "question_score": 0, "tags": "plugins, categories, woocommerce offtopic, e commerce, bug" }
is_main_query() not working for WP REST API My initial situation is, that I have a custom post type `events` which are - who would have thought - events. There is a custom UI (backend) where the user can enter multiple dates. Each date is then saved as post meta as a timestamp. I am then using `pre_get_posts` (and a few other filters/actions) to change the query so the posts are displayed based on that timestamp. This is working perfectly when calling the default post type archive page (< We are currently developing an app for mobile phone which then should display the events. We are using the WP REST API to retrive the event data. The problem is that `is_main_query()` returns always false when using the REST API. Does anybody know how i can bypass this problem?
To answer the question directly - The REST API do not initialize a main query, therefor there should not be any for requests coming that way. What you should do is to create your own end point and server what ever custom data you need on it. Modifying the REST API, while possible, violates the whole idea of having a consistent and documented API in the first place.
stackexchange-wordpress
{ "answer_score": 2, "question_score": 1, "tags": "custom post types, wp query, archives, rest api, custom post type archives" }
Where to get the unsaved list of widgets in customizer? In the customizer, whenever I add a new widget (but before I save/publish the changes) I would like to get the number of widgets in that sidebar area. Once the changes have been saved and the widgets are saved to the DB, I can use the `wp_get_sidebars_widgets` (called in the `init` hook, where it registers my widgets) to count all the widgets for each sidebar area, I've taken a look at the `wp.customize.Widgets` and the `wp.customize.WidgetCustomizerPreview` objects and they do not look like they will give me what I need. Where in the JS is this information saved?
You can get the list of widgets in a sidebar via: wp.customize('sidebars_widgets[sidebar-1]').get() This is a list of the widgets' IDs. The `sidebars_widgets[sidebar-1]` is the setting ID for the sidebar. Replace `sidebar-1` with the ID of your sidebar. So to get the count just do: wp.customize('sidebars_widgets[sidebar-1]').get().length If you want to listen for when a widget is added or removed to a sidebar, you can `bind` to the `setting` to listen for changes, like this: wp.customize( 'sidebars_widgets[sidebar-1]', function( sidebarSetting ) { sidebarSetting.bind( function( newWidgetIds, oldWidgetIds ) { console.info( { added: _.difference( newWidgetIds, oldWidgetIds ), removed: _.difference( oldWidgetIds, newWidgetIds ) } ); } ) } );
stackexchange-wordpress
{ "answer_score": 6, "question_score": 3, "tags": "widgets, theme customizer" }
how to show a custom taxonomy as dropdown in wordpress? I want to show a custom taxonomy in the name of custom_tax in a plugin option page as dropdown that user can select terms of taxonomy. I know that I can use wp_dropdown_categories() but I don't want show the terms of category taxonomy. I'm going to show my custom taxonomy terms as dropdown. Is there any function to do that? or no how can I do that?
`wp_dropdown_categories()` has the `taxonomy` parameter, which defaults to `category`, but can be used to retrieve custom taxonomies. Exemplary usage: wp_dropdown_categories([ 'taxonomy' => 'custom-taxonomy-name' ]);
stackexchange-wordpress
{ "answer_score": 1, "question_score": 0, "tags": "menus" }
Adding Html in text editor automagically adds undesirable paragraphs when publishing When I write pages, I want to code my own HTML to accomplish the design that I get. For that I use "Text" editor view instead of "Visual" editor. I do not switch between them and when publishing the code, unfortunately, for some reason it automatically adds `<p></p>` and `<br>` elements breaking the design. Am I missing some checkbox to tick to avoid this? Is there any other solution that start using a plugin like `raw html` ?
While this sounds strange behavior, it does sound like you are doing it wrong. The wordpress "text" editor is not an HTML editor and should not be a replacement for one. It is useful for fixing whatever can not be done with the visual editor, but no more. If you need a specific design which is just impossible to even get close to achieve with the visual editor, you should just create a page template for it. (It is unlikely that a author which do not understand HTML will be able to maintain the changes you are trying to do now, so no flexibility will be actually lost)
stackexchange-wordpress
{ "answer_score": 1, "question_score": 0, "tags": "html editor" }
Get category id of next / prev post inside the_post_navigation I would like to get_the_category inside the_post_navigation. I created a custom field on Categories to assign a hex color to each category. I would like to use this color as the next / prev link background color when hovering on the post navigation. How can I get the id of the category of the "next" or "prev" post? I should clarify that every post has only two categories and I am only trying to get the id of the second category.
Here was my final solution: $next_post = get_next_post(); if (!empty( $next_post )){ $next_categories = get_the_terms($next_post->ID,'category'); $next_cat_data = get_option('category_'.$next_categories[1]->term_id); if (isset($next_cat_data['hex'])){ echo "<style>div.nav-next:hover{background-color:".$next_cat_data['hex'].";} div.nav-next:hover span.post-title, div.nav-next:hover span.meta-nav {color:#f8f7f4;}</style>"; } } $previous_post = get_previous_post(); if (!empty( $previous_post )){ $prev_categories = get_the_terms($previous_post->ID,'category'); $prev_cat_data = get_option('category_'.$prev_categories[1]->term_id); if (isset($prev_cat_data['hex'])){ echo "<style>div.nav-previous:hover{background-color:".$prev_cat_data['hex'].";} div.nav-previous:hover span.post-title, div.nav-previous:hover span.meta-nav {color:#f8f7f4;}</style>"; } }
stackexchange-wordpress
{ "answer_score": 0, "question_score": 0, "tags": "categories" }
Feed cache fallback - A feed could not be found Trying to refactor a feed plugin to fallback on cache if source is unavailable (ex: for maintenance). Started using `fetch_feed($url);` which affords more flexibility in terms of cache. But unsure of how to structure the fallback.
Sounds like you are looking at it from a very low layer POV. `fetch_feed` provides caching so you will not need to wait for a response on possibly every page load. Therefor, as long as there is a cache you are unlikely to even **want** a message to be sent and obviously you are not handling any actual result. It is unlikely that you will want to hurt your server with a faster refresh rate just to be able to properly detect the conditions on the other side. What you should do is to handle the situation of not getting a reply, which is probably equal to empty feed, to supply the defaults you want.
stackexchange-wordpress
{ "answer_score": 0, "question_score": 0, "tags": "cache, feed, simplepie" }
Shortcode to insert menu in page body? I need to insert a menu in the text of one page. I found these two plugin but none of them work. Both of them haven't been updated for 6 years: < < I found this code to create my own shortcode function print_menu_shortcode($atts, $content = null) { extract(shortcode_atts(array( 'name' => null, 'class' => null ), $atts)); return wp_nav_menu( array( 'menu' => $name, 'menu_class' => $class, 'echo' => false ) ); } add_shortcode('menu', 'print_menu_shortcode'); And then shortcode should be: [menu name="-your menu name-" class="-your class-"] It works but the class is not printed at all. **What is wrong in the function?** I need to print the class.
That code should work. Are you usign "myclass" as the class and not ".myclass"? Is this for a specific use where class will always be the same? If you're only looking to ever use this on one place, you can do this: function print_menu_shortcode($atts, $content = null) { extract(shortcode_atts(array( 'name' => null, 'class' => null ), $atts)); return wp_nav_menu( array( 'menu' => $name, 'menu_class' => 'myclass', 'echo' => false ) ); } add_shortcode('menu', 'print_menu_shortcode'); Then change the section 'menu_class' => 'myclass' with the class you need. this will avoid having to use the class. Again, don't use the "." in front of the class here. Short code usage: [menu name="menu_name"]
stackexchange-wordpress
{ "answer_score": 11, "question_score": 3, "tags": "functions, shortcode" }
default favicon for a theme? I am developing a theme and I wonder if there is a possibility to have a default favicon. Details: The theme already has support for adding favicon and users can go to admin->customize->site identity and select an image for favicon. Is possible that the theme shows a default favicon in case user still hasn't got to it?
You have to change the defualt Site Icon using the Customizer API. $wp_customize->add_setting( 'site_icon' , array( 'default' => YOUR_IMAGE_URL_HERE, ) );
stackexchange-wordpress
{ "answer_score": 3, "question_score": 4, "tags": "theme development" }
Disable Top Nav Bar on Mobile I've created a site (www.smartgrowtheconomics.com) using the 2017 theme plus some extra CSS that looks fine on a desktop and tablet, but persistently shows a blue dropdown menu and search bar on a smartphone. I've tried some CSS-ery, including .navigation-top { display: none; } and .main-navigation { visibility:hidden; } but not managed to remove the bar, menu, and search bar. I don't know JS, but I've pasted snippets with instructions before. Thanks!
If you want to get rid of the whole blue section at the top (menu and a search input field), you should add this to your CSS: .menu-search { display: none; }
stackexchange-wordpress
{ "answer_score": 0, "question_score": 0, "tags": "menus, css, navigation, mobile, screen layout" }
Create a "Reject" action for comments? I'd like editors on my site to be able to reject comments, alongside approve/unapprove/spam/trash, both individually and in bulk. The reason is that all of our comments have to be approved before they go live, but we tend to keep rejected comments around (we often flag them with a reason why they're being rejected). We have multiple users who handle comment moderation, so just "unapproving" a comment makes it hard to tell whether it has been reviewed or is still pending. I am curious whether it is feasible to create something like this (ideally with a dropdown of reasons why a comment is being rejected that a moderator could choose from) within WordPress, or whether I'd be better off just sending rejected comments to the Trash and disabling the automatic delete.
It's currently not that easy to create new comment statuses in WordPress. Comments in WordPress have a field `comment_approved` which can have a value of `1`, `0`, `spam` or `trash`. In your case I'd probably leverage the existing trash functionality and store the rejection reason as comment meta. That's similar to how anti-spam plugins like Antispam Bee store the spam reason as comment meta and display it separately in the admin.
stackexchange-wordpress
{ "answer_score": 1, "question_score": 2, "tags": "comments" }
Update postmeta Parent when post_status child change I have custom status = completed. I want to set automatically when child post update status 'completed'. their parent's postmeta also change. here my code: add_action('save_post', 'update_status_parent_when_completed'); function update_status_parent_when_completed(){ /** Ensure this is the correct Post Type*/ if($post_type !== 'screening') return; if ($post->post_status == 'completed'){ $parent_id = get_the_ID($post->post_parent); update_post_meta($parent_id, 'screening_status', 'screen'); } } but nothing happen with parent_post. Please teach me the correct way.
From WP 3.7 you have the option to hook to the `save_post` hook directly for you post_type. For example: function update_post_parent_status_on_complete( $post_id ) { if(!isset($post)) $post = get_post($post_id); // checking the status you want and also that has a parent if ($post->post_status == 'completed' && $post->post_parent !=0 ){ $parent_id = $post->post_parent; update_post_meta($parent_id, 'screening_status', 'screen'); } } add_action('save_post_screening', 'update_post_parent_status_on_complete');
stackexchange-wordpress
{ "answer_score": 0, "question_score": 1, "tags": "custom post types, posts, customization, post meta, post status" }
Custom data-id wp_enqueue_script I need to insert something like this in wordpress: <script id="customID" data-name="customDataName" src=" I am using wp_enqueue_script but I can not find how to add an id and a data-name to the script
`script_loader_tag` filter was introduced in WordPress 4.1: <?php add_filter( 'script_loader_tag', 'my_script_attributes', 10, 3 ); function my_script_attributes( $tag, $handle, $src ) { // change to the registered script handle, e. g. 'jquery' if ( 'MY_SCRIPT_HANDLE' === $handle ) { // add attributes of your choice $tag = '<script id="customID" data-name="customDataName" src="' . esc_url( $src ) . '"></script>'; } return $tag; }
stackexchange-wordpress
{ "answer_score": 4, "question_score": 2, "tags": "plugins, plugin development, wp enqueue script" }
Open and closed function I've written my first php function and I'm not too sure whether I've created it in the best way. I want to display "our lines are open" from 9 - 5 and "our lines are closed" from 5 on wards. Here's the code I've written. <?php function myTest() { $open = "our lines are open"; $closed = "our lines are closed"; if (time() >= strtotime("09:00:00")) { echo "<p>$open</p>"; if (time() >= strtotime("17:00:01")) echo "<p>$closed</p>"; } } I'm also not sure how I would display this in a text field on wordpress, I've added the functions into function.php file.
$open = "our lines are open"; $closed = "our lines are closed"; if ( time() >= strtotime( '09:00:00' ) && time() <= strtotime( '17:00:00' ) ) { echo $open; } else { echo $closed; } Somethinh like this should help you.
stackexchange-wordpress
{ "answer_score": 1, "question_score": 0, "tags": "php, functions" }
wp_insert_post is not creating revision in database I am creating custom frontend post submission form. I am using `wp_insert_post` for creating new post. The function is working fine but it is not creating the revision record in database. Following is my code. I want record of every revision made in the post. Plz Help… Thanks… <?php if (isset($_POST['submit_post']) ) { $my_post = array( 'post_title' => wp_strip_all_tags( $_POST['post_title'] ) ); wp_insert_post( $my_post ); } ?> <form method="POST"> <div class="form-group"> <label for="post_title">Post Title</label> <input type="text" class="form-control" name="post_title" placeholder=""> </div> <button type="submit" name="submit_post" class="btn btn-default">Submit Post</button> </form>
`wp_insert_post()` currently doesn't create a revision for a newly created post. This is a known limitation (or feature?) in WordPress core and has been reported before on WordPress Trac. To work around this, you could try to manually call `wp_save_post_revision()` after inserting your post.
stackexchange-wordpress
{ "answer_score": 2, "question_score": 1, "tags": "wp insert post" }
Is possible dequeue/remove style from wp_footer() hook and add on wp_head() hook? I need unregister this enqueue style of wp_footer() hook and add it to the top of site with hook wp_head(), this is possible? I'm optimizing my theme to validate in W3C, and one of the requirements of W3C is that all styles are within the tag `<head></head>`... I am using an specific plugin called `Crayon Syntax Highlighter`, and this plugin are inserting a style at the bottom of the page (probably using `wp_footer()` hook). The name/id of script is `crayon`: ![enter image description here]( I've tryed all this functions but no success: wp_deregister_style( 'crayon' ); wp_dequeue_style( 'crayon' ); remove_action( 'wp_enqueue_style' , 'crayon' , 10 ); wp_deregister_style( 'crayon-css' ); wp_dequeue_style( 'crayon-css' ); remove_action( 'wp_enqueue_style' , 'crayon-css' , 10 );
If you look at the source code, you can see that `wp_enqueue_style( 'crayon' )` is called in `Crayon::enqueue_resources()` which itself is called either from either `Crayon::the_content()` or `Crayon::wp_head()`. The code in `Crayon::wp_head` is: if (!CrayonGlobalSettings::val(CrayonSettings::EFFICIENT_ENQUEUE) || CrayonGlobalSettings::val(CrayonSettings::TAG_EDITOR_FRONT)) { CrayonLog::debug('head: force enqueue'); // Efficient enqueuing disabled, always load despite enqueuing or not in the_post self::enqueue_resources(); } Which will enqueue the style only when certain settings are enabled. Otherwise, the style will only be enqueued from `the_content` filter which fires after `wp_head` has already been output. So your two options are: 1. Have the CSS enqueued on all pages in the header 2. Have the CSS enqueued only on necessary pages but in the footer
stackexchange-wordpress
{ "answer_score": 3, "question_score": 1, "tags": "filters, hooks, actions, footer, wp head" }
WP_Query: custom orderby (not ASC nor DESC) How do I get a custom `orderby` in `WP_Query` (not `ASC` nor `DESC`)? So, order have to be not alphabetically, nor numerical. It have to be custom. For example I want to sort by post's meta field `thing` in next order: 1. Bag 2. Car 3. Apple So all bags come first, then cars then apples.
You probably can find some way to make MySQL do the sort for you, but an alternative approach is to make it into an ASC/DESC order by adding additional meta in which you put a numeric sort order value based on whether it is apple, bag, etc and update it when the post is saved. Than all you need to do is to sort by the "sort" meta field.
stackexchange-wordpress
{ "answer_score": 0, "question_score": 0, "tags": "wp query, order" }
How to delete read more span on single post view? How could I complete delete following line on single post view? <p><span id="more-XXX"></span></p> I need to delete whole span tag. Is there any other option than preg_replace?
As stated in the docs, if the quicktag `<!--more-->` is used in a post to designate the “cut-off” point for the post to be excerpted, `the_content()` tag will only show the excerpt up to the `<!--more-->` quicktag point on non-single/non-permalink post pages. WordPress adds `<span id="more-' . $post->ID . '"></span>` to the content in this case. Since there's no content in the `<span>` (check out the code), you can easily remove the `<span>` by filtering the content: add_filter( 'the_content', function( $content ) { return str_replace( '<span id="more-' . get_the_ID() . '"></span>', '', $content ); } Note that this causes the Read More link not to jump to the area where you inserted `<!--more-->` anymore. An easier way to achieve this would be to use the `the_content_more_link` filter and remove the `#more-<post_id>` part from it there. There are a few examples in the Codex for that.
stackexchange-wordpress
{ "answer_score": 2, "question_score": 1, "tags": "templates, single, read more" }
Shortest way to install WP-CLI That's the shortest way I know to install the WordPress shell extension **WP-CLI** : curl > /usr/local/bin/wp && chmod +x /usr/local/bin/wp Is there an even shorter way? Note: I use Ubuntu 16.04.
Downloading the Phar file is the recommended installation method for most users. As you showed, it's basically just one line. It can't really get shorter than that. And the steps make sense: download the file, make it executable and move it to the right location. There are alternative ways to install WP-CLI though. For example, if you're using Composer, and have something like `~/.composer/vendor/bin` in your PATH (or `C:\Users\you\AppData\Roaming\Composer\vendor\bin` on Windows), you can just run: composer global require wp-cli/wp-cli To update everything globally, run `composer global update`. Alternatively, on Debian or Ubuntu you can just download and open one of the .deb packages: < On macOS you can install WP-CLI via Homebrew: `brew install homebrew/php/wp-cli`
stackexchange-wordpress
{ "answer_score": 4, "question_score": 1, "tags": "wp cli, linux, command line" }
Failed to load resource admin-ajax.php I'm still new to WordPress. I have been encountering `Failed to load resource: the server responded with a status of 404 (Not Found)` error and its pointing it in `wp-admin/admin-ajax.php`. I have check the folder and `admin-ajax.php` is there. I also tried calling `admin-ajax.php` using `network_admin_url()` instead of `admin_url()`. But I still keeps on having that error. Is there anyway to solve it? Thank you very much for your help. Here is the sample code var ajaxurl = '<?php echo admin_url('admin-ajax.php'); ?>'; $.ajax({ type: "POST", url: ajaxurl, cache: false, data: { action: 'getInfo' }, success: function(data) { mIDs= mDisplay(data); } }).done(function( msg ) { });
I contact the hosting provider regarding it. They advise me to fix the .htaccess which causing the error.
stackexchange-wordpress
{ "answer_score": 2, "question_score": 2, "tags": "wp admin" }
WordPress select query issue Trying to fetch all data from `wp_postmeta` table. I am trying to fetch first `meta_key` column value. so I am running this query. When I am using `print_r` then all data showing but when I am using foreach loop then its not working. <?php global $wpdb; $myrows = $wpdb->get_results( "SELECT * FROM wp_postmeta" ); foreach($myrows as $value){ echo $value->sleeps; }
One more for the pot: `$wpdb->get_col` can be used to return a "single dimensional" array of all values set for "sleeps" global $wpdb; $values = $wpdb->get_col( "SELECT meta_value FROM wp_postmeta WHERE meta_key = 'sleeps'" ); echo implode(',', array_unique($values) );
stackexchange-wordpress
{ "answer_score": 0, "question_score": 0, "tags": "php, mysql" }
singular posts using archive styling I am making a wordpress twenty seventeen child theme. In this theme I have a archive page for all posts with the category "all". Every post has a sub category. On the archive page all posts are showed like this: screenshot of archive page content. Now if i click one of the posts and go to a single post page it shows the post like this: screenshot of single post page. Is there a way of organizing the posts so that i would be able to edit them based on the sub category.
if you are not aware of WordPress template structure. < < WordPress follow a hierarchy for post/page templates archive.php for your archive pages of post and category. single.php for your every WordPress single post. you can adjust your single.php code to make single page HTML different then archive page. In your case to separate styling for the same HTML of single and archive page, why not your style archive and single page separate by taking body classes as a parent? your attribute will have different class on single and archive page
stackexchange-wordpress
{ "answer_score": 1, "question_score": 0, "tags": "posts, categories, child theme, archives, theme twenty seventeen" }
Redirect https://www.subdomain.domain.com is not redirecting to subdomain.website.com Hi i have a website example.com, i want to redirect my < to subdomain.example.com Its working when some one write url without https:// (e.g < But not working when we tried to load website < Here is the error showing on page: > This server could not prove that it is www.subdomain.example.com; its security certificate is from *.website.com. This may be caused by a misconfiguration or an attacker intercepting your connection.
You don't appear to have a valid SSL cert installed on your server that covers the hostname `www.subdomain.example.com`, ie. the `www` sub-subdomain`. The only way to resolve this and not get the _browser warning_ is to install a valid certificate on your server that covers the required hostname. Otherwise, unless the user accepts this invalid certificate in their browser (which they should not), then the request never actually reaches your server, so never sees the redirect.
stackexchange-wordpress
{ "answer_score": 1, "question_score": 0, "tags": "htaccess, ssl" }
Make RSS feed only accesible by Mailchimp I'm developing a private site for a customer (only accesible by loggin in) and I would like to make the RSS feed only accesible by MailChimp. I know how to take the feed out of the auth_redirect and is_user_logged_in function, but I don't know how to make that specific URL only accesible by MailChimp (if there's a way)
Finally, the solution has been, as birgire pointed out, creating a custom feed and only allowing access to that URL: // Create new feed add_action('init', 'customRSS'); function customRSS(){ add_feed('supersecretfeed', 'customRSSFunc'); } function customRSSFunc(){ get_template_part('rss', 'supersecretfeed'); } Then, as the site is private, I had to allow public access to that specific URL, adding the is_feed option: // Ban non logged users function protect_whole_site() { if(! is_page( 'wp-login.php' ) && ! is_feed('supersecretfeed') && ! is_user_logged_in() ) { auth_redirect(); } }
stackexchange-wordpress
{ "answer_score": 2, "question_score": 0, "tags": "customization" }
create a select input with menus created on a custom options page In a custom wordpress page, I want the user to select a desired menu from a custom options page. Something like that ![enter image description here]( Here I record the fields, now I only have one field type text to do some tests function register_my_cool_plugin_settings() { register_setting( 'my-cool-plugin-settings-group', 'menu_site' ); } Now, I create the input registered above <td> <input type="text" name="menu_site" value="<?php echo esc_attr( get_option('menu_site') ); ?>" /> </td> I want a select field with data coming from the wordpress itself, in my case, I want it to list the menus created by me
Hi see wp_get_nav_menus() You can set `$args` parametr. The same as `$args` to `get_terms()` function. function will return Array ( [0] => stdClass Object ( [term_id] => 3 [name] => Menu 1 [slug] => menu-1 [term_group] => 0 [term_taxonomy_id] => 3 [taxonomy] => nav_menu [description] => [parent] => 0 [count] => 1 ) [1] => stdClass Object ( [term_id] => 4 [name] => Menu 2 [slug] => menu-2 [term_group] => 0 [term_taxonomy_id] => 4 [taxonomy] => nav_menu [description] => [parent] => 0 [count] => 2 ) )
stackexchange-wordpress
{ "answer_score": 1, "question_score": 1, "tags": "php, customization, menus" }
Customize "Continue Reading" text I am using "twenty seventeen" theme for my blog. I need to change text of "Continue reading" link. Could you please help me? Thanks, Dmitriy Reznik
The solution (or problem) is not limited to the 2017 theme. This is something you can add to any theme. Since it involves changing the `functions.php` file, you should first make a Child Theme of the 2017 theme. (Ask the googles how to do that....and why you would use a Child Theme rather than changing the theme code.) In fact, if you had asked the googles the same question, the first result would have been the Codex, where all is revealed. < .
stackexchange-wordpress
{ "answer_score": 2, "question_score": 1, "tags": "themes" }
Different string for specifed post type on posts listing at homepage I use below code to list custom post types on homepage beside standard posts <?php $args = array('post_type' => array( 'post', 'gallery_posts' )); ?> <?php $query = new WP_Query( $args ); ?> <?php if ( $query->have_posts() ) : ?> <?php while ( $query->have_posts() ) : $query->the_post(); ?> <?php _e('Read More', ''); ?> <?php endwhile; ?> <?php endif; ?> What i should to do for change 'Read more' text for second type of post while looping?
You can check the post type in a conditional and echo a different 'read more' text based on this. Your `$query` is a `WP_Query` object and has a `$post` property. This is a `WP_Post` object of the current post and it has a `$post_type` property. You can access it directly with `$query->post->post_type` to check the type. So your code would be something like: <?php $args = array('post_type' => array( 'post', 'gallery_posts' )); ?> <?php $query = new WP_Query( $args ); ?> <?php if ( $query->have_posts() ) : ?> <?php while ( $query->have_posts() ) : $query->the_post(); ?> <?php if ( 'post' === $query->post->post_type ) : ?> <?php _e('Read More', ''); ?> <?php elseif ( 'gallery_posts' === $query->post->post_type ) : ?> <?php _e('View More', ''); ?> <?php endif; ?> <?php endwhile; ?> <?php endif; ?> References: * `get_post_type()`: < * `WP_Query`: < * `WP_Post`: <
stackexchange-wordpress
{ "answer_score": 3, "question_score": 1, "tags": "wp query, query, listing" }
Can I assign a Folder for Post Formats, without it affecting WordPress' fallback/hierarchical system? I have created a few Post Format Templates Files. `format-aside` and `format-audio` etc. At present, I am using `<?php get_template_part (‘format’,get_post_format()) ;?>` to call such Templates. In an organisational effort, I am looking to place all of my Post Format files, into a folder, entitled `post-formats` and then call each Post Format, using the following entry: `<?php get_template_part (‘post-formats/format’,get_post_format()) ;?>` Whilst this works, I was wondering if this was seen as bad practice. Is anyone aware of any issues this may concern, such as affecting WordPress' fall back/hierarchy system?
In general, "bad practice" is so common in the wordpress ecosystem, you will have to do something really bad for anyone to actually signal you out for doing it ;) If you are the developer and maintainer of the theme, you should develop it in a way which will be easy for you to maintain in the long run, regardless of what other people's preferences are. If someone else is going to maintain it, keep as much as you can to the structures used by the core themes. That said, in this specific case, even if they don't do it this way, it looks easy enough to understand by anyone that had ever worked with wordpress themes.
stackexchange-wordpress
{ "answer_score": 1, "question_score": 0, "tags": "templates, hierarchical, post formats, template hierarchy" }
if statement with is_active_sidebar() I found a code in my sidebar-content-bottom.php in the theme itself that I don't really understand. if ( ! is_active_sidebar( 'sidebar-2' ) && ! is_active_sidebar( 'sidebar-3' ) ) { return;} I know that both conditions must be true that the if function activates return; But what does it return then? Two times true on the page?
It doesn't return anything, it just jumps back out of the function. That's basically "If this is neither `sidebar-2` nor `sidebar-3`, don't continue in this function".
stackexchange-wordpress
{ "answer_score": 3, "question_score": 0, "tags": "php, theme development, sidebar" }
iframe not showing on frontend when using a CMB2 field I have a custom field manually coded using CMB2: < Here is the code: $cmb_pages_customtext->add_field( array( 'name' => esc_html__( 'Content', 'defaulttheme' ), 'id' => $prefix . 'customtext_content', 'type' => 'wysiwyg', 'sanitization_cb' => false, )); I want to be able to add an iframe to the custom field. When I add the iframe code to the field, it saves it in the page edit screen but the iframe doesn't display when viewing the actual page. Is there something I need to add to get the iframe to display on the actual page?
I actually figured out the problem. It was a wp_kses_post function that was the cause. The wp_kses_post function was stripping the iframe tag. Obviously I removed the wp_kses_post function.
stackexchange-wordpress
{ "answer_score": -1, "question_score": -2, "tags": "plugins, metabox, iframe" }
Wordpress custom slug rewrite I have custom post type 'gallery' with the same slug. For other functionality I user `/gallery?tags=snow` and this is ok. I need custom slug like `/gallery-snow` who point on `/gallery?tags=snow` For example: add_filter('query_vars', 'add_show_var', 0, 1); function add_show_var($vars){ $vars[] = 'tags'; return $vars; } add_rewrite_rule('^gallery-snow/?$','index.php?post_type=gallery&tags=snow','top'); But not working. Any help?
I find answer add_action('query_vars','foo_set_query_var'); function foo_set_query_var($vars) { array_push($vars, 'tags'); return $vars; } add_rewrite_rule('^gallery-snow/?','index.php?post_type=gallery&tags=snow','top'); And in page use get_query_var('tags')
stackexchange-wordpress
{ "answer_score": 2, "question_score": 0, "tags": "custom post types, url rewriting, rewrite rules" }
How to translate WordPress Emails? I'm running a multilingual site, and I want the emails sent to the user to be in their language. The scheme I already have is the following: 1. The website determines the user's country through their IP. 2. The website redirects the user to the site's version of the language of their country (eg. if the IP detected is from France, then it redirects the user to a WPML french version of the site). The problem is that I want to have emails translated as well, based on the IP of the user. (eg. the user registers through < then the email sent to him for completing his registration should be in French.) I have WPML and Loco Translate activated for translation, along with Geo Redirect to redirect users to various site's languages. Is this achievable? and how?
I managed to do so using a plugin called **IP2Location Redirection** , then it worked well for me. It turned out that **Geo Redirect** hasn't been compatible with latest versions of Wordpress.
stackexchange-wordpress
{ "answer_score": 0, "question_score": 1, "tags": "email, translation, multi language, plugin wpml" }
Will cron job run if page loaded is being served from cache? As a cron job does not run until a page load request comes, what will happen in case page-loaded is being served from cache by some caching plugin? Will WordPress still run a cron job that is scheduled to run in this case?
It depends on the plugin and the cache method you are using. For example, as far as I remember, WP Super Cache offers two different cache methods: 1. PHP Cache 2. HTML Cache Using the first method creates PHP cache files that still load WordPress's functions, but do not go through the whole loading process. If this is the case, it means that the PHP functions are executed, and your cron job will probably be processed. However, since the cron jobs are usually in the theme's `functions.php` file, and the PHP cache file is usually a PHP template cache, there is a chance that it won't trigger. You should have a closer look at the generated PHP cache files. The second method simply creates status HTML files that are served directly. There is no PHP involved in this, so no cron job will be executed.
stackexchange-wordpress
{ "answer_score": 4, "question_score": 2, "tags": "plugin development, cache, wp cron, cron, plugin w3 total cache" }
WP Core Update Issue Hi I am having some issues with my wordpress install. I am getting 500 server error on my wp-admin page. From my error logs I am getting some issues with Yoast SEO and compatibility. From sources it is recommended to update my wordpress version. (Running wp multisite) I run `wp core update` but it is not working properly `The address 127.0.0.1 is not in the database. Updating to version 4.9.4 (en_US)... Using cached file '/home/ubuntu/.wp-cli/cache/core/wordpress-4.9.4-no-content- en_US.zip'... Unpacking the update... Error: Could not create directory.` Could be file permissions? Any help? Cheers
If you're running v4.9.3, you will unfortunately have to do a manual upgrade to v4.9.4. According to its release announcement, v4.9.3 contained a bug that produces an error when you attempt to upgrade it from within the dashboard.
stackexchange-wordpress
{ "answer_score": 1, "question_score": 0, "tags": "errors, updates" }
WP_MEMORY_LIMIT didn't work in wp-config, only within default-constants.php i have already searched here and tried a lot of things, but my problem still is "alive" It is possible to set `WP_MEMORY_LIMIT` within the default-constants.php and this works fine, but every time I update wordpress I have to make this setting again. So my wp-config.php does not overwrite the setting in the default-config.php. The wp-config-file was created directly from wordpress automatically. I have checked this thread, my setting for `WP_MEMEORY_LIMIT` is directly below `WP_DEBUG` and before `ABSPATH` is defined. $table_prefix = 'hp365_01_'; define('WP_DEBUG', false); define(‘WP_MEMORY_LIMIT’, ’128M’); /* That's all, stop editing! Happy blogging. */ Maybe somebody has the same problem ?
Your code appears to be using he incorrect quote characters. You have `’` instead of `'`. This can happen if you copy it from a site where the quotes have been converted to ‘fancy quotes’ by the publishing platform but the author didn’t catch it. So replace define(‘WP_MEMORY_LIMIT’, ’128M’); With define('WP_MEMORY_LIMIT', '128M');
stackexchange-wordpress
{ "answer_score": 2, "question_score": 0, "tags": "wp config, memory" }
How to display a linked category name with get_the_category I a code snippet with this bit included... $output .= '<li><a href=" ' . get_the_permalink() .' ">' . get_the_title() .'</a> ' . get_the_category() .' '. get_the_time('d M Y') . '</li>'; it works great except the `get_the_category` bit
`get_the_category()` returns the array of `WP_Term` objects. So, // get all categories objects $categories = get_the_category(); // get the first category name if ( ! empty( $categories ) ) { $category = $categories[0]->name; } $output .= '<li><a href=" ' . get_the_permalink() . ' ">'; $output .= get_the_title() . '</a> '; $output .= $category .' '; $output .= get_the_time('d M Y') . '</li>';
stackexchange-wordpress
{ "answer_score": 2, "question_score": -1, "tags": "categories" }
Query for specific custom field I'm working to build a food blog and I'd like to add the feature that permits to logged users to save in a specific area all favorite recipes. I created two specific post types (likes and recipes) and a custom field that makes the association (favorite_recipe_id) and control if the user has already added that specific recipe in his list. Now I'd like to create the area to show to the user all the recipes added in the list: I'm a little bit confused , anyone should help me to find a right way to follow? Thanks a lot
Data associated to a user can be saved in user meta. Save the recipe post IDs in an array for the user. $my_favs = array( 42, 23, 99 ); update_user_meta( get_current_user_id(), 'user_favs', $my_favs ); Then to query all recipe posts with those IDs, pass the array as the `post__in` argument to `WP_Query`: $my_favs = get_user_meta( get_current_user_id(), 'user_favs', true ); $args = array( 'post_type' => 'recipe', 'post__in' => $my_favs, ); $recipes = new WP_Query( $args );
stackexchange-wordpress
{ "answer_score": 1, "question_score": 0, "tags": "customization, query" }
Count total number across post types I am using this code to count number of posts for one custom post type. What's the best way to change this to sum up together 3 different custom post types? function get_all_them_ven_posts(){ $post_type = 'restaurants'; $count_posts = wp_count_posts( $post_type ); $published_posts = $count_posts->publish; return $published_posts; }
Why not just get the count for each post type and sum them? function get_all_them_ven_posts(){ $count= 0; $post_types = [ 'postType1', 'postType2', 'postType3' ]; foreach( $post_types as $post_type ) { $count_posts = wp_count_posts( $post_type ); $count = $count + $count_posts->publish; } return $count; }
stackexchange-wordpress
{ "answer_score": 2, "question_score": 1, "tags": "posts, count" }
'Post-thumbnails' feature does not seem to register We are trying to change the crop style of the thumbnails attached to the posts on our website. This is the code we have used to declare a new image-size: <?php /** --- Thumbnails configuration **/ function add_custom_sizes() { add_theme_support('post-thumbnails', array('post', 'page', 'custom-post-type-name')); // Featured size add_image_size( 'featured-big', 400, 400, true ); // width, height, crop } add_action('after_setup_theme','add_custom_sizes'); ?> We then call this image-size while printing out one of our thumbnails: <?php the_post_thumbnail( 'featured-big' ); ?> However the thumbnail doesn't seem to be cropped correctly. The parameter `true` in the `add_theme_support` function is supposed to 'Hard Crop' the image, however the image is 'Soft' cropped, incorrectly. Any clues?
Image sizes and cropping settings do not apply retroactively: images that were present on your site before you made this change are not affected. Your new settings will only apply to images you upload afterwards, because image are cropped at the time of uploading. You can either try to upload a new image, or you can trigger the re-cropping of previously uploaded images to apply your new settings with the very handy Regenerate thumbnails plugin.
stackexchange-wordpress
{ "answer_score": 3, "question_score": 0, "tags": "php, theme development, thumbnails, post thumbnails" }
Relative URLs for a particular custom post type? Is it possible to make URLs relative for just a singular custom post type? I used these 2 lines in make just my custom post types to use relative URLs. add_filter( 'post_type_link', 'wp_make_link_relative' ); // Custom post type link add_filter( 'post_type_archive_link', 'wp_make_link_relative' ); // Post type archive link This worked great, until I realized I had a trickle down problem of my events no longer resolving properly if they were shown on a sub-domain. My site has a few different mapped sub-domains, so I'm now looking to narrow my add_filter to just the custom post type I need instead of all of them.
At @milo's suggestion, I used the post_type_link example and adapted it to my needs. This made it so only my chosen post type would be relative, while leaving any other custom post types functioning as usual. function make_yourposttype_relative ( $url, $post ) { if ( 'yourposttype' == get_post_type( $post ) ) { add_filter( 'post_type_link', 'wp_make_link_relative' ); // Custom post type link add_filter( 'post_type_archive_link', 'wp_make_link_relative' ); // Post type archive link } return $url; } add_filter( 'post_type_link', 'make_yourposttype_relative', 10, 2 );
stackexchange-wordpress
{ "answer_score": 1, "question_score": 1, "tags": "custom post types, url rewriting" }
How I can split text in the_content() into 2 columns? I need to split one paragraph of text into two columns in wordpress `the_content()`; I tried different tutorials, but they not work for me. Also I can't use shortcodes. Here how I need to make it done: ![enter image description here]( Now I have all of the text in one column.
Did you try css? <div class="columncontent"> <?php the_content(); ?> </div> Then the css: .columncontent { column-count: 2; } Depending on your theme, you could just find a div already surrounding your content too. There is all sorts of magic there! < The only thing I would suggest is that you use media queries, as the 2 columns may be a bit much on mobile. You'll have to decide that and at what breakpoint you want to use.
stackexchange-wordpress
{ "answer_score": 4, "question_score": 2, "tags": "the content, columns" }
Remove Header from specific page in Twenty Ten Hello I am using the Twenty Ten theme on a WordPress 4.9.1 I need to remove the header image for just some specific pages, but not the whole site. Is there a custom css code I can use for this? I tried some other I found in searches, but had no luck. Thank you.
Get the id number of the pages from which you want to remove the header images, then you can hide them with CSS. This may not, arguably, be the optimal method,but it'll work: So, say the page ID #s are 42, 56, and 506. .page-id-42 #branding img, .page-id-56 #branding img, .page-id-506 #branding img { display: none; } Here's an image file - note that on any page, if you look at the inspector, the page-id-# class will be shown on the `body` tag, like page-id-445 here: ![enter image description here](
stackexchange-wordpress
{ "answer_score": 2, "question_score": 0, "tags": "theme twenty ten" }
correct path for enqueue script in WordPress I have this action: add_action( 'wp_enqueue_scripts', 'my_custom_script_load3' ); function my_custom_script_load3(){ wp_enqueue_script( 'my-custom-script3', '/members/user.js' ); } It works great when I have it in functions.php of my root directory WordPress installation. But I also have a second WordPress installation which is in it's own directory, on the root: /second-wordpress-site/ I have this action also installed in this second WordPress site in functions.php In this second WordPress site, the action keeps pulling the script up like: /second-wordpress-site/members/user.js instead of how it should be: /members/user.js Any suggestions on the correct syntax for the site, so the path is correct? I've tried several path variations, with no luck. Thanks for any help.
Is your second WordPress installation accessible using URL? If yes then you can use the following tricks add_action('wp_enqueue_scripts', 'op_enqueue_scripts'); function op_enqueue_scripts() { wp_enqueue_script( 'my-script-from-2nd-site', ' array( 'jquery' ), '1.0', true ); }
stackexchange-wordpress
{ "answer_score": 0, "question_score": 0, "tags": "wp enqueue script" }
Loop on a wordpress Page instead of content coming from the WP text editor I have created a page template: <?php /* Template Name: homedefault */ ?> But Instead of text coming from here i.e. wp editor: ![enter image description here]( I want it to come from the loop: <?php if ( have_posts() ) : while ( have_posts() ) : the_post(); ?> <?php $post_id = get_the_ID(); ?> <?php get_template_part('content','home'); ?> <?php endwhile; ?> <?php endif; ?> But the loop doesn't seem to be working. Is it possible at all? P.S. → loop is for the posts → ![enter image description here](
On your custom page template, the default loop is working and that's why the loop is fetching content from the page. You need a custom query in this case. Here's the code. <?php $query = new WP_Query( array( 'post_type' => 'post', 'post_status' => 'publish', ) ); if ( $query->have_posts() ) { while ( $query->have_posts() ) { $query->the_post(); get_template_part( 'content', 'home' ); } }
stackexchange-wordpress
{ "answer_score": 5, "question_score": -2, "tags": "php, functions, loop, templates, page template" }
How to exclude certain code from style.css? I have a code in my theme's stylesheet that looks like this. I would like for my code to not use the width property that is set in here. Deleting is not the option as that would be only temporary solution until the next update of my theme. What can i do, so that this with property is not used? @media (max-width: 991px) and (min-width: 544px){ .footer-bottom-widgets .columns { position: relative; float: left; min-height: 1px; padding-left: .9375rem; padding-right: .9375rem; width:33.333%; } }
I would not suggest creating a child theme to override a single CSS line. You can simply use the theme customizer and add your CSS to the additional CSS box. Most CSS properties accept an `unset` or `inherit` value. So, you can paste the following code into the additional CSS box: @media (max-width: 991px) and (min-width: 544px){ .footer-bottom-widgets .columns { width: unset; } } Since the additional CSS is added as inline, the priority is higher than the original CSS, which will override the original styles.
stackexchange-wordpress
{ "answer_score": 0, "question_score": 1, "tags": "css" }
How to add post title below the featured image in the plugin code? I'm trying to modify the 'display random posts' plugin. In the following code I would like the output display to show list of posts with the featured image and the title of the post below it. Currently this code displays only the featured image in front end. How do I add the post title below the image? $string .= '<ul>'; while ( $the_query->have_posts() ) { $the_query->the_post(); $string .= '<li><a href="'. get_permalink() .'">'. get_the_post_thumbnail() .'</a></li>'; } $string .= '</ul>';
Personally I would not modify the plugin, as you'll just lose all your changes on each and every update. But if you insist, just change line 4 to `$string .= '<li><a href="'. get_permalink() .'">'. get_the_post_thumbnail() .'</a><h6>'. get_the_title() .'</h6></li>';` Then you can target those h6s with CSS
stackexchange-wordpress
{ "answer_score": 0, "question_score": 0, "tags": "post thumbnails" }
Can I have an additional functions.php file in Wordpress? There're quite a lot of functions, and so, does my theme, it all gets a little cluttered even with all the comments. Additionally, every time the theme is updated, the new functions.php file would replace the current one. So, it becomes a pain. Hence, I thought, would it be possible to have a 2nd/3rd functions.php file? Using PHP include or require function. That way, I can categorise the functions and they won't be affected on theme update. So, <?php include 'functions_1.php' ?> Thanks,
You can get rid of the theme update situation by using a child theme. Your child theme will work as an extension of the parent theme that you update often. You can learn more about child theme from here. But if you don't wanna use child theme then yes, you can add as many additional functions file as you want. A regular `include` or `require` will just work fine. You can include file using a relative path or you can use `get_template_directory()` function for an absolute path. For instance include get_template_directory() . '/inc/functions-1.php'; // if it's inside inc directory include get_template_directory() . '/functions-1.php'; // Or if it's not inside any directory
stackexchange-wordpress
{ "answer_score": 2, "question_score": 0, "tags": "functions, include" }
Moving wp-content folder to public_html I want to move my `wp-content` folder up to `public_html`. I put this in `wp-config.php` (before the "That's all, stop editing!" line): define( 'WP_CONTENT_DIR', dirname(__FILE__) . '/public_html/wp-content' ); define( 'WP_CONTENT_URL', ' ); My site is in a subfolder and so my purpose in doing this is to gett media file URLs without the subfolder name. But it totally didn't work. Now the whole site won't load and I get this: "ERROR: The themes directory is either empty or doesn’t exist. Please check your installation."
I was able to fix this problem by using this code instead of the one above: define('WP_CONTENT_DIR', $_SERVER['DOCUMENT_ROOT'] . '/wp-content'); define('WP_CONTENT_URL', ' . $_SERVER['HTTP_HOST'] . '/wp-content');
stackexchange-wordpress
{ "answer_score": 0, "question_score": 0, "tags": "uploads, media" }
How to hyperlink both post thumnail image and post title text in wordpress? In the output of following code currently only the post title is getting hyperlinked to the main post but not the image. I want both the image and title to hyperlink to the main post. $string .= '<li>'. get_the_post_thumbnail() .'<a href="'. get_permalink() .'" >'. get_the_title() .'</a><hr/></li>'; I tried: $string .= '<li>'<a class="nana" href="'. get_permalink() .'" >. get_the_post_thumbnail() .. get_the_title() .'</a><hr/></li>'; but it breaks down the whole site. I'm a beginner. Any help appreciated.
You had the right idea when you put the thumbnail between the opening and closing `<a>` tags, but the dot operators and the quotes are wrong, which is why it breaks down the site. This would be the proper way to write it: $string .= '<li>' .'<a class="nana" href="'. get_permalink() .'" >'. get_the_post_thumbnail() . get_the_title() .'</a><hr/></li>';
stackexchange-wordpress
{ "answer_score": 2, "question_score": 1, "tags": "permalinks" }
Moving the WordPress dashboard avatar over the admin menu Is there any documentation on moving the avatar image to the top of the menu area in the WordPress dashboard?
You could make a custom menu item using a plugin called Admin Menu Editor And you could hide the avatar using CSS, to do this you could use a plugin to insert CSS in the admin dashboard or just create your own admin.css file and insert it putting this in your functions.php file: function registerCustomAdminCss(){ $src = "path/admin.css"; $handle = "customAdminCss"; wp_register_script($handle, $src); wp_enqueue_style($handle, $src, array(), false, false); } add_action('admin_head', 'registerCustomAdminCss'); Where path/admin.css is the path to your admin.css file
stackexchange-wordpress
{ "answer_score": 1, "question_score": 0, "tags": "admin menu, avatar" }
How to select which thumbnails sizes are displayed in srcset I know that Wordpress has its way of letting the browser decide which image to download depending on the viewport via the srcset. I also know that I can use the_post_thumbnail function and specify a custom size, like this: the_post_thumbnail('my-custom-size'); Now, what I would like to achieve is being able to specify a list of custom sizes (of different aspect ratio from the original image), and letting the browser decide with one to use based on the viewport. I DON'T want to just add a custom size to the list of possibilites in srcset, I want to choose the whole list of available sizes. I DON'T want to override the general setting of srcset of the entire website. I want to specify this list of sizes only in one section. Is this possible?
The 2nd argument of `the_post_thumbnail()` is an array of attributes and values, so you can just set your own `srcset` attribute that way: the_post_thumbnail( 'my-custom-size', array( 'srcset' => wp_get_attachment_image_url( get_post_thumbnail_id(), 'my-other-custom-size' ) . ' 1000w', ) );
stackexchange-wordpress
{ "answer_score": 1, "question_score": 0, "tags": "post thumbnails, responsive" }
Automatically change home page I am using a static page as my homepage. I would like to be able to create a new version of the homepage and add it to some kind of publication queue so the new version gets published at midnight. How would I achieve this?
Maybe you can use this plugin: Front Page Scheduler > Front Page Scheduler let you choose some page to be shown as the front page of your site during a specific daily period, in specific week days. Since version 0.1.4, you can even create a set of “rules”, choosing specific front pages for different days and perio
stackexchange-wordpress
{ "answer_score": 0, "question_score": 0, "tags": "homepage" }
Can (slow) Internet speed get you a 500 server error? Not sure if my host or config fails sometimes or if my slow internet contributes to a server error (500).
No. 500 error will return when you have server error. PHP error, etc. See response code reference. > The HyperText Transfer Protocol (HTTP) 500 Internal Server Error server error response code indicates that the server encountered an unexpected condition that prevented it from fulfilling the request. > > This error response is a generic "catch-all" response. Sometimes, server administrators log error responses like the 500 status code with more details about the request to prevent the error from happening again in the future.
stackexchange-wordpress
{ "answer_score": 2, "question_score": -2, "tags": "errors, server" }
stop login if user_status equal zero i'm trying to create simple approval users plugin to denay or approve new user, so i used default user_status to do that, what i'm asking for how can i stop the login form to save session and add error msg if user_status = 0, something like that if($user_status == '0'){ //stop login sessiong echo $error_msg.'waiting for approval'; }else{ //run session } is there anyway to do that
The `user_status` field isn't used by core, so you could use it for your own purposes. Although there may be side effects if WP ever decides to reuse it in the future. The `authenticate` filter fires before the user is authenticated. You can hook into that filter and return a `WP_Error` object to prevent the user from logging in. function wpse_293904_authenticate( $user, $username, $password ) { $user_status = get_custom_user_status_from_username( $username ); if( ! $user_status ) { $error = new WP_Error(); $error->add( 403, 'Oops. Some error message.' ); return $error; } return $user; } add_filter( 'authenticate', 'wpse_293904_authenticate', 20, 3 );
stackexchange-wordpress
{ "answer_score": 3, "question_score": 1, "tags": "users, login, user meta, post status" }
Insert ads below the title I'm creating a plugin for insert ads. I want to insert ad below the title. I'm using the theme MH Magazine Lite Im doing my plugin like this: function diww_pre_content($content) { $pre_content = 'ads_up'; $pre_content .= $content; return $pre_content; } add_filter( 'the_content', 'diww_pre_content' ); But, this shows the ad, below the feature image (inside the post) instead of title. ![enter image description here]( Any idea, how can i do that? Thanks.
You can use `mh_post_header` action hook to add your ads content after the post title. Check the following code snippet for help add_action( 'mh_post_header', function() { echo 'Ads content goes here'; }, 5 );
stackexchange-wordpress
{ "answer_score": 1, "question_score": 0, "tags": "plugins, ads" }
Woocommerce exclude specific categories products from related products I've added the following code to my child theme's function.php to exclude the category "workshops" from displaying Woocommerce Related Products. How would I add in a 2nd category (ie. events) to this code? Thanks. add_action( 'wp', 'vn_remove_related_products' ); function vn_remove_related_products() { if ( is_product() && has_term( 'workshops', 'product_cat' ) ) { remove_action( 'woocommerce_after_single_product_summary', 'woocommerce_output_related_products', 20 ); } }
add_action( 'wp', 'vn_remove_related_products' ); function vn_remove_related_products() { if ( is_product() && has_term( array('workshops', 'events'), 'product_cat' ) ) { remove_action( 'woocommerce_after_single_product_summary', 'woocommerce_output_related_products', 20 ); } } Function `has_term()` can pass first parameter as array with terms.
stackexchange-wordpress
{ "answer_score": 1, "question_score": 1, "tags": "woocommerce offtopic" }
Can't update WordFence Options, clear data manually I ran across this problem today. Found enough bits on Stack Overflow to finally get me there, but figured I'd post a coherent answer to my question. Problem: I can't save changes in WordFence, and need it to clear it's data on uninstall so I can reinstall it cleanly. I found the data in the database table wp_wfConfig, but all settings are saved as `blob` or `longblob`. How can I change the settings so the data all clears on deleting the plugin?
I found a post on Stack Overflow advising that converting a column from `blob` to `text` should result in no data loss. I didn't really care about data loss since I wanted to remove the plugin data anyway, so I gave it a shot. On the Structure tab in phpMyAdmin, I edited the val column and changed it to text. Then I found the option for deleteTablesOnDeact and changed the value from 0 to 1. After doing this, I was able to deactivate the plugin and the tables were all removed.
stackexchange-wordpress
{ "answer_score": 2, "question_score": 0, "tags": "database, mysql, phpmyadmin" }
Post thumbnail throwing size limit parameters in <img> <ul class="widget_image_2"> <?php while ( $query->have_posts() ) : $query->the_post(); ?> <li> <?php the_post_thumbnail( 'medium'); ?> <a href="<?php the_permalink(); ?>"> <?php echo wp_trim_words( get_the_title(), $number_of_words ); ?></a> </li> <?php endwhile; ?> </ul> the above code is generating this in the browser: <img width="300" src=" class="attachment-medium size-medium wp-post-image" alt="" srcset=" 300w, 768w, 1024w" sizes="(max-width: 300px) 100vw, 300px"> But these two are not allowing the images to take full width in the responsive version(600px): sizes="(max-width: 300px) 100vw, 300px" width="300" Is there a method to get rid of this? I also checked CSS there is nothing written in the CSS to impose such limitations.
Change image size `medium` to `large` e.g `the_post_thumbnail( 'large' )`. If you enlarge `300px` image to `600px` your image will be distorted. Or if you need more control on image size then you have to register a new image size using `add_image_size()`.
stackexchange-wordpress
{ "answer_score": 2, "question_score": 0, "tags": "post thumbnails, images" }
Custom Post Type featured option I have created a Custom Post Type called `Products`. Now I need a functionality that will allow me to select or check a product as featured. There can be only one featured product. When one product is selected the others are deselected automatically. This featured product will be displayed on homepage. **Question:** What is the best way to store the `featured_product_id` to identify the one that is featured?
There is no need to store product setting product wise as there will be only one featured product. You can store the `featured_product_id` in **options table**. And whenever a product is featured you just override the record in the options table, that why you can avoid the deselecting hassle of previously selected featured product.
stackexchange-wordpress
{ "answer_score": 0, "question_score": 0, "tags": "custom post types, plugin development, options, featured post" }
How can I dequeue a Plugin Stylesheet? I am currently using a Plugin, which has created a Stylesheet within the following directory: `/wp-content/uploads/plugin-name/css`. I would like to remove this Plugin's Stylesheet, since it is being called after my Custom Stylesheet, where the Plugin is performing unwanted overrides of the Custom Stylesheet. Instead, I want to remove the Plugin's Stylesheet; copying only required styles into the Custom Stylesheet. I tried placing the following into the `functions.php` file, within the Child Theme: <?php function dequeue_dequeue_plugin_style(){ wp_dequeue_style( 'plugin-css' ); //Name of Style ID. } add_action( 'wp_enqueue_scripts', 'dequeue_dequeue_plugin_style', 999 ); ?> Unfortunately, this did not work. Is anyone able to see if I have gone wrong with my Code or whether Plugin Styles have priority over all files within a Child Theme etc.
My error. All I had to do was knock off the `-css` and it worked. Working code: <?php function dequeue_dequeue_plugin_style(){ wp_dequeue_style( 'plugin' ); //Name of Style ID. } add_action( 'wp_enqueue_scripts', 'dequeue_dequeue_plugin_style', 999 ); ?>
stackexchange-wordpress
{ "answer_score": 3, "question_score": 4, "tags": "plugins, wp enqueue script, wp enqueue style, css" }
Object of class WP_Post could not be converted to string while trying to console.log wp_get_nav_menu_items I am trying to fetch items from currently assigned menu. Wordpress documentation says wp_get_nav_menu_items($menu) returns array of menu items. Just to test have a fetched proper menu items I wanted some kind of output. Coming from JS I tried to console log it like this: `$menu = wp_get_nav_menu_items(3); foreach ($menu as $menuItems) { ?> <script> console.log(<?php echo $menuItems?>); </script> <?php }` Afterwards I get error on line where I'm console logging $menuItems: > "Object of class WP_Post could not be converted to string" Is there any other way to log on frontend or to see the contents of $menu variable? I also tried to echo $menu directly but not working. Thanks in advance for any help.
I've figured that using `print_r` will output array via `console.log`
stackexchange-wordpress
{ "answer_score": 0, "question_score": -1, "tags": "php, javascript" }
Place a button besides "add new" Is there hook to place a button besides "add new". I'm trying to use it on a custom post type. I'm currently using this code. I don't know if it's the proper way though. function custom_js_to_head() { ?> <script> jQuery(function(){ jQuery("body.post-type-wpr_guest_suit .wrap h1").append('<a href="index.php?param=your-action" class="page-title-action">List View</a>'); }); </script> <?php } add_action('admin_head', 'custom_js_to_head'); ![enter image description here](
The 'proper' way would be to use add_action() See: < The closest hook for your need would be 'edit_form_top' You could do something like this function add_your_button(){ echo '<a href="index.php?param=your-action" class="page-title-action">List View</a>'; } add_action('edit_form_top', 'add_your_button'); That would achieve: ![enter image description here]( The catch is that there is a hr tag after the Add New so your new button is going to get pushed down the screen by the hr and also alerts eg Autosave alerts. I'd suggest you use the magic of CSS to position your button absolutely. Something like: .custom-class-for-your-button { position: absolute; top: 1.6em; left: 14em; } Though make sure you provide CSS to support the full range of screen sizes your editors are likely to edit the site with.
stackexchange-wordpress
{ "answer_score": 0, "question_score": 0, "tags": "custom post types" }
How to I retrieve the ID from the Posts page? I am creating some custom meta boxes in my theme to allow user to insert their own custom meta description and keywords overrides (no I will not use a plugin for it). I am having an issue with the posts page as when I'm trying to retrieve the ID for it by using: $custom_seo_desc = \get_post_meta( $this->post->ID, 'custom_page_desc' ); I keep returning the ID of the first post that appears on the posts page, not the actual ID of the parent page itself. Therefore I cannot seem to set any custom meta data description. I've done some google searches and I'm stumped for an answer, all I get is articles on how to locate page and posts ID, nothing for a designated posts page. Does anyone out there have a solution?
You can use `get_queried_object_id()` to retrieve the page ID. $custom_seo_desc = \get_post_meta( get_queried_object_id(), 'custom_page_desc' ); You can verify the page for posts ID by looking at the option `page_for_posts`. $posts_page_id = get_option( 'page_for_posts' );
stackexchange-wordpress
{ "answer_score": 2, "question_score": 0, "tags": "posts, custom field, metabox, post meta, id" }
Insert Link to Audio versus Embed Audio Player I've run into a very odd problem. One of my authors will upload an audio file in the Media Manager, and instead of giving the option to embed a media player, it just inserts a link to the audio file. If he deletes the link and reopens Media Manager, the Embed Media Player option reappears. I have not been able to replicate this in any other user account, and I've had him log out, clear his cache and cookies, and log back in to no avail. Any ideas?
Haven't been able to figure this one out, so I'm going to go ahead and close it. Seems to be localized to a specific computer/user account.
stackexchange-wordpress
{ "answer_score": 0, "question_score": 0, "tags": "media, media library, visual editor, embed, audio" }
Why is it important to deactivate a plugin before deleting it? I stumbled across this page, where it says that `wp plugin delete` does this: **Deletes plugin files without deactivating or uninstalling.** Why is it important to deactivate a plugin before it is deleted? Is it a formality or can something terrible happen?
Generally, plugins have some functionality hooked onto the deactivation action. This could be clearing cache, resetting options, you name it. Therefore the best practice is to deactivate them first, so they have the opportunity to clean up and execute whatever functionality they have hooked onto the deactivate event. Now if the plugin is broken and can't be executed, or if the deactivation function does something you don't want or is broken in itself, you might need to delete it without running that functionality. In my experience, nothing bad really happens, except some junk files being left. This can be different depending on the plugin however, so always excercise caution with this type of forced deletion.
stackexchange-wordpress
{ "answer_score": 21, "question_score": 11, "tags": "plugins, wp cli" }
Redirect the single product page link to the shop page I am using the WooCommerce plugin. I want to redirect the user to shop page if they try to access the product link. For example, this is the product link: < and shop page link: < Now when a user tries to visit a product link, should be redirected to the shop page! Mainly, I don't want anyone to have an access to the product page! Please, can someone tell me how can I achieve this? Thanks in advance!
You can try using `template_redirect` action hook to check if the current page is product page and after that, you can redirect the user to your shop page. Paste this code into your functions.php add_action('template_redirect','custom_shop_page_redirect'); function custom_shop_page_redirect(){ if (class_exists('WooCommerce')){ if(is_product()){ wp_redirect(home_url('/shop/')); exit(); } } return; } I have not tested it, but hope it will work for you.
stackexchange-wordpress
{ "answer_score": 5, "question_score": 1, "tags": "woocommerce offtopic, template redirect" }
Automatically set all <p> tags to have a height of 0 if there is no content inside the <p> tag I have noticed Wordpress loves to insert `<p>` tags everywhere. This can be both helpful and completely annoying... The issue is sometimes i will catch empty `<p>` tags inserted into the html, which cause a spacing issue (creating more white space on the page..) Instead of disabling the `<p>` tag styles all together. I would like to set the height of all `<p>` tags to `0px` if the `<p>` tag is empty (has no text inside). Can i do this without jquery or javascript? PHP maybe? If jquery is the only option, you may post this as the answer. Thanks for any help!
I always like to use this in my css: p:empty{ height: 0; // or display: none; } Keep in mind that this only removes absolutely empty paragraph tags. If there is a space or anything it will not be targeted. More about the empty selector here
stackexchange-wordpress
{ "answer_score": 3, "question_score": 0, "tags": "php, jquery, css" }
Edit pagination text in the get_the_posts_pagination function I want to edit the screen_reader_text in link-template.php Can I do this in a theme so it wont get overwritten on update. It seems a filter is the best option but I cant find documentation on what filter to use. Here is the code I want to change from link-template.php: if ( $GLOBALS['wp_query']->max_num_pages > 1 ) { $args = wp_parse_args( $args, array( 'mid_size' => 1, 'prev_text' => _x( 'Previous', 'previous set of posts' ), 'next_text' => _x( 'Next', 'next set of posts' ), 'screen_reader_text' => __( 'Posts navigation' ), ) ); How can I change Posts navigation to something else, via functions or another way?
You can modify `screen_reader_text` argument when invoking the_posts_pagination() wrapper function in your theme files: <?php the_posts_pagination( array( 'mid_size' => 2, 'prev_text' => __( 'Back', 'textdomain' ), 'next_text' => __( 'Onward', 'textdomain' ), 'screen_reader_text' => __( 'Whatever', 'textdomain' ), ) ); ?> Search for `the_posts_pagination` in your template files, and adjust texts as you wish. ![enter image description here](
stackexchange-wordpress
{ "answer_score": 2, "question_score": 2, "tags": "filters, pagination" }