INSTRUCTION
stringlengths
11
999
RESPONSE
stringlengths
0
999
SOURCE
stringlengths
16
38
METADATA
dict
WP_Query() load selected post I need to load a selected post in a ajax function, I have some problems writing the appropriate query that calls the post i'm pointing <?php $pb_id = $_POST['post_id']; $pb_details_args = array( 'p' => $pb_id, ); $pb_details_query = new WP_Query( $pb_details_args ); while ($pb_details_query -> have_post() ): $pb_details_query -> the_post(); echo '<h4>' . get_the_title() . '</h4>'; endwhile ?> at the moment i have this piece of code but i think is basically entirely wrong The page where i need to laod this is < in the box over the footer. you can see the entire code at < the code i'm referring is in homus-web/wp-content/themes/homus-theme/single_pb_post_details.php
You don't need a query if you the know the post ID: <?php $post_id = absint( $_POST['post_id'] ); if ( ! $post = get_post( $post_id ) ) exit; // Error if ( $post->post_status !== 'publish' ) exit; // Might want to prevent script kiddies from accessing private content echo '<h4>' . get_the_title( $post ) . '</h4>';
stackexchange-wordpress
{ "answer_score": 1, "question_score": 0, "tags": "php, posts, wp query" }
Homepage meta title and description not showing in search engines? I have just launched a new website and have been having trouble locating it anywhere on search engines, so I decided to do a google search for **_"site:mysitename.com"_** to show all of the results from my website. The homepage is the first page to be displayed, however, it is saying the meta title is a title of one of the blog posts on the website. Once I click on the homepage link and view the source the meta title is set to **_Home | My Site Name_** as I have set it to. So my question is why in a search engine is the title of my homepage showing up as one of the blog posts names?
Google doesn't always show the meta descriptions and title's that you set. This is taken directly from Google's Search Console help pages. > Google's generation of page titles and descriptions (or "snippets") is completely automated and takes into account both the content of a page as well as references to it that appear on the web. The goal of the snippet and title is to best represent and describe each result and explain how it relates to the user's query. <
stackexchange-wordpress
{ "answer_score": 2, "question_score": 0, "tags": "title, seo, google search" }
Bootstrap grid system is not working in my Wordpress theme I'm a long time Wordpress user but this is the first time I dared to build my own theme (while following a tutorial though). I'm trying to use Bootstrap as the layout tool for the theme, but for some reason I can't get it to work. Here is the work-in-progress: < I'm expecting the three divs with class="col-md-4"> to sit next to each other horizontally. Instead they stack on top of each other. Is my Bootstrap not loading properly here or what could be the issue?
It is not really a Wordpress related question, more a html/css question for Stack Overflow. But i did look at your code, you are using Bootstrap 2.3. */ * Bootstrap v2.3.2 * * Copyright 2013 Twitter, Inc * Licensed under the Apache License v2.0 * * * Designed and built with all the love in the world by @mdo and @fat. */ You should load the latest version (3.3.6) to use `col-md-4` for your containers.
stackexchange-wordpress
{ "answer_score": 1, "question_score": 0, "tags": "theme development, twitter bootstrap" }
How are updates to the style.css file in child theme recognized? When I update the _style.css_ in my active child theme, the changes are not immediately picked up. I tried doing a `touch` on the file, but the results have been inconsistent. It worked once, but did not work the next time. The changes were recognized after waiting for some time (~15 minutes). I checked the file timestamps and they Is there something else that I need to do to let WordPress know that the style.css file has been updated for the current theme? Is the browser's concept of time involved in the decision to include changes from the style.css file? Note: I am using the `wp-enqueue-style()` approach instead of the `@import` method for including the parent style.css. Update: I do refreshes on the browser side every time I update style.css.
The culprit was the server-side cache system used by my service provider (SiteGround). Their cPanel has a cache-flush device; using it solved the problem: ![enter image description here]( This stackoverflow question also helped. Here's a link to the SiteGround page describing the system: SiteGround static cache
stackexchange-wordpress
{ "answer_score": 1, "question_score": 2, "tags": "child theme, wp enqueue style" }
Custom post type based on existing one Im using a theme that comes with a portfolio post type and portfolio categories taxonomy. My problem is that I want my site to have 3 portfolio sections, each with its own category list. Can I somehow "clone" the theme`s portfolio type and categories (and the admin section to edit them)?
No, you will need to create them (you can do so using plugins). Another approach is creating a different taxonomy to use as the section, or even a custom post field to filter, but in all of them you will need to edit your theme code.
stackexchange-wordpress
{ "answer_score": 0, "question_score": 0, "tags": "custom post types, custom taxonomy" }
Show recent products first but "sold out last" in query I am using WooCommerce and would would like to show the "out of stock" products last in the query on the archive page. How can I do that? Currently we are making the newest product show first with the following custom query: add_action( 'pre_get_posts', 'mik_exclude_category' ); function mik_exclude_category( $query ) { if ( $query->is_main_query() ) { $query->set( 'orderby', 'date' ); $query->set( 'order', 'DESC' ); } } So, we would like to do both. Show the newest products first, but show "out of stock" products last no matter how new they are. Sincerely, Mika
If we only have two stock statuses, namely `outofstock` and `instock`, we can very easily achieve sorting with `pre_get_posts` add_action( 'pre_get_posts', function ( $q ) { if ( !is_admin() // Target only front end && $q->is_main_query() // Only target the main query && $q->is_post_type_archive() // Change to suite your needs ) { $q->set( 'meta_key', '_stock_status' ); $q->set( 'orderby', 'meta_value' ); $q->set( 'order', 'ASC' ); } }, PHP_INT_MAX ); You should adjust that to your needs
stackexchange-wordpress
{ "answer_score": 3, "question_score": 1, "tags": "query, woocommerce offtopic" }
Storefront Child Theme show product attribute i'm building a child theme for storefront, how to display the attributes of a product on list product page other than the product name and price? example this list only show product name and price, i want show "desc" or "size" here : ![enter image description here](
You do not need to code externally for that. Please refer the screenshots given below: ![Add product attributes from the dashboard]( Add product attributes from the dashboard as shown in the above image. ![Attributes will be shown under Additional Information]( At the front end product attributes will be shown under the section _Additional Information_. Hope your problem is solved, if not please post a comment below. **Answer for updated question:** Since you want to show product attributes on product list page, just add following lines in your functions.php add_action('woocommerce_after_shop_loop_item_title', 'show_attr'); function show_attr() { global $product; $product->list_attributes(); } Product list page will look like this: ![Product attributes will look like this](
stackexchange-wordpress
{ "answer_score": 0, "question_score": -4, "tags": "woocommerce offtopic" }
custom post type archive page url to point to Page permalink I wish that my 'custom post type archive page' would point to Page. The situations is as follows: I have `Page` in Wordpress with permalink ` This page shows list of posts with custom post type = `vmgallery`. I have custom logic for this page that is working fine. From another view, this page works like "custom post type archive page", because it displays all posts for given custom post type vmgallery. Currently, if user goes to < wordpress is loading archive page (archive.php), instead, I wish ` page is loaded. How to achieve this?
You have multiple options here. **1\. Define post type archive slug on post type registration** By setting `'has_archive' => 'galleries'` you can define custom post type archive slug. Check documentation. Then you can delete your page "galleries" then add & customize the `archive-post_type.php` **2\. Disable default archive for post type** Disable the archive by setting `'has_archive' => false` then keep the page for the post type archive. **3\. Redirect archive requests to your page** You can permanent redirect default archive request to your page. function archive_to_custom_archive() { if( is_post_type_archive( 'post_slug' ) ) { wp_redirect( home_url( '/galleries/' ), 301 ); exit(); } } add_action( 'template_redirect', 'archive_to_custom_archive' ); > I will say the first method is good!
stackexchange-wordpress
{ "answer_score": 11, "question_score": 3, "tags": "custom post types, custom post type archives" }
How to remove/hide the predictive autocomplete popup when I type in the tag/term metabox When I start to type in a few letters in the tag or term metabox (in the post edit page) there is a predictive autocomplete popup thingy containing other tags/terms to choose from. How do I disable/hide this?
There is no filter or way to stop those Ajax calls. However, you can alter the response of Ajax call by using filter `term_search_min_chars`. Which is actually to customize minimum number of characters after that Ajax will print the response. So we can make it `0` to never print the response! /** * Remove tag search suggestions * @param int $tax The minimum number of characters required. Default 2. * @return int */ function remove_tag_suggestions($tax) { //You can place your condition if you want! return 0; } add_filter('term_search_min_chars', 'remove_tag_suggestions'); PS: I am not sure why do you want to remove this wonderful feature!
stackexchange-wordpress
{ "answer_score": 2, "question_score": 2, "tags": "metabox, tags, terms" }
Regex works in regexr, but not if I filter content I want to filter the content of everypost and add classes to my links depending on certain conditions. At the moment I just want to filter all href attributes from the content and change them. add_filter( 'the_content' , 'add_link_classes' ); function add_link_classes( $content ) { $url_regex = "/\href\=\"(http|https)\:\/\/.+?(?=[\"])\"/"; preg_match_all( $url_regex, $content, $matches ); var_dump( $matches ); return $content; } var_dump returns this: array(2) { [0]=> array(0) { } [1]=> array(0) { } } But as you can see, the same expression works as expected on regexr.com.
Per comments, it's best to use single quoted strings for regexs in PHP (then only backslash and single quote are special), and only backslash as necessary, eg in this case $url_regex = '/href="(http|https):\/\/.+?"/'; (leaving out the positive lookahead which isn't needed here).
stackexchange-wordpress
{ "answer_score": 0, "question_score": 0, "tags": "functions, filters, content, regex" }
Wordpress Child Theme Template auth_redirect wrapper I'm successfully utilizing a child theme in Wordpress. I would like to create a page template that simply forces login for any visits to the pages where this template is in use. (Simply need to add `<?php if (!is_user_logged_in()) { auth_redirect(); } ?>` to a separate template.) Copying the existing template down to the child theme makes updating tedious and prone to failure for such a simple call. However, I cannot find a way to create a new template that calls a parent template. I will admit that I may not be understanding an existing call, but I have been unable to see any way to do this. Setting URL filters for every page is not a usable option. I'm also unable to use slugs, as they are already in use for another purpose.
I solved the issue at hand by creating a Custom Field of requires_login and setting it to "true", then adding the following code to functions.php: function require_login() { if ( get_post_meta(get_the_ID(), requires_login, true) && ! is_user_logged_in() ) { auth_redirect(); } } add_action('template_redirect', 'require_login'); Marking this as answered, as it solved the problem. However, if someone were to show how to have an inherited template, I'd consider changing the answer. Many thanks to @Milo for pointing me in the right direction. Apologies to @userabuser for the unintentional disappearing code trick.
stackexchange-wordpress
{ "answer_score": 0, "question_score": 0, "tags": "templates, child theme, child pages, authentication" }
wp_category_checklist won't show up for non-admin users I have a product registration page with a form in which I use `wp_category_checklist()` to make my users select categories. This works great only, I just today noticed that only admin's can use the checklist! **For normal users the whole category list doesn't even show up!** Is there any workaround for this? I've googled but couldn't find it. What I mean with " _it doesn't show up_ " is that every element below the `wp_category_checklist` in the DOM gets deleted. E.g. If I have <body><? wp_category_checklist(); ?> <div> one million div's here</div> </body> It won't show me anything on the page, the `<body>` would be blank.
If you want to use the wp_category_checklist on pages that also non-admin users access. You have to include the following php: <? require_once(ABSPATH.'wp-admin/includes/template.php'); ?> Credit to Majick!
stackexchange-wordpress
{ "answer_score": 0, "question_score": 0, "tags": "categories, admin, forms" }
Random posts in WP_Query when searching by tag I have a section that want to include featured posts. I want to look for featured posts based on tag. For example, I want to fetch all the latest posts that have the featured tag. I use the following query to do that $featPosts = new WP_Query(array( 'posts_per_page' => 5, 'tag_slug__in' => 'featured', //The tag-slug 'post_status' => 'publish', 'order_by' => 'date', 'order' => 'DESC', 'ignore_sticky_posts' => 1 )); wp_reset_query(); The issue here is that some random posts appear that don't have the featured tag. Any idea why this might be happening? Any help appreciated :)
`tag_slug__in` should be an array, not a string, that is why your query fails 'tag_slug__in' => ['featured'], // Requires PHP 5.4+, use array( 'featured' ) pre 5.4
stackexchange-wordpress
{ "answer_score": 0, "question_score": 0, "tags": "wp query, query, tags" }
How to check if "is single" page I know – at first glance the problem may seem easy to solve – and I hope it is – I just can't figure out where/ how to check if I'm really on a single page, or just rendering a single page in the loop. I basically need to alter the page title of CPT pages. This is what i have tried so far: function event_page_title($title) { global $post; if ( ( 'event' == $post->post_type ) && ( is_singular() ) ) { $title = "Title: " . $title; return $title; } add_filter('the_title', 'event_page_title', 0); Problem is: the title is also altered in listings (`WP_query`) – although not in archive pages. I hope somebody can point me some direction? Thank you!
You can use `is_singular()` with post types like this: if( is_singular('event') ) { // We are in single view of event post type } So, your code could be: add_filter( 'the_title', 'event_page_title' ); function event_page_title( $title ) { if ( is_singular( 'event' ) ) { $title = "Title: " . $title; } return $title; }
stackexchange-wordpress
{ "answer_score": 4, "question_score": 1, "tags": "custom post types, loop, filters" }
WP_Query offset argument does not work I want to display all posts starting from a certain offset, my query is: WP_Query( array( 'posts_per_page' => -1, 'offset' => 20, 'cat' => 5, ) ); This query shows all posts without starting from the offset value. Whys is that?
The `offset` index for WP_Query generally works with pagination. When you set pagination to a `-1` the function assumes you're getting all posts and there will be no pagination or offset. So to counteract this you would set the `posts_per_page` to a high number like 999. Reading the Function Reference on WP_Query the pagination section says: > `'posts_per_page'=>-1` to show all posts ( **the`'offset'` parameter is ignored with a -1 value**). Set the ‘paged’ parameter if pagination is off after using this parameter.
stackexchange-wordpress
{ "answer_score": 25, "question_score": 10, "tags": "posts, wp query, offsets" }
Disable plugin on admin page I have just made a plugin which shows me fb icon on fixed position. My problem is that the plugin shows on each page include administration panel there I don't want to show. It may be visited only at user side pages. Can you help? ![Screenshot](
use `if(!is_admin())` to check your code run only if you Not in admin area
stackexchange-wordpress
{ "answer_score": 0, "question_score": 0, "tags": "plugins, wp admin" }
Is accessing theme and using customizer GPL distribution? I am theme developer and I want to make a "demo" website, where people to which I give password will have access to nearly all theme functions (except theme editor) -> they won't have full admin rights. They will use it only to evaluate theme. Problem is that, I don't want to them to have the right to a have copy -> to not distribute theme to them. My question is whether using customizer and theme options counts as redistribution, therefore use of GPL which force me to give them the source code which I don't want to.
In my understanding (and I'm not a lawyer, etc etc), this would not count as distribution. I make this distinction mainly based on the fact that a separate GPL-flavoured license actually exists where this _would_ count as distribution - the GNU Affero General Public License. GitHub's choosealicense.com states: > GNU AGPLv3 is distinguished from GNU GPLv3 in that hosted services using the code are considered distribution and trigger the copyleft requirements. (< Therefore, as long as you're using the GPL and not AGPL, I believe what you're doing wouldn't count as distribution. Remember though that once you sell your theme under the GPL, the buyer can do whatever they like with it - including posting the source code online for free.
stackexchange-wordpress
{ "answer_score": 0, "question_score": 1, "tags": "theme development, themes, theme customizer, licensing" }
ACF allow zero as a value I would like to have 0 to 5, and "n/a" as possible values, however this code will output "n/a" when I want it to output a zero. How can I get it to output "0"? ("n/a" is the placeholder if no value is set.) Difficulty: <?php if(get_field('difficulty')) { echo the_field('difficulty');} else { echo "n/a"; } ?>
In PHP, `0 == false == [] == '' == null`. A simple check to check if a variable or condition has a value will return `false` if the value is equal to 0. For `0` to return true as a valid value, you would need to make use of strict comparison by using the identical ( _`===`_ ) operator. Just remember, if you use `===`, not only the value must match, but the type as well, otherwise the condition will return false. If your values are a string, you should use `'0'`, if they are integer values ( _which I doubt as custom field values are strings as single values_ ), you should use `0`. You can do the following check $difficulty = get_field( 'difficulty' ); if ( $difficulty // Check if we have a valid value || '0' === $difficulty // This assumes '0' to be string, if integer, change to 0 ) { $value = $difficulty; } else { $value = 'n/a'; } echo 'Difficulty: ' . $value;
stackexchange-wordpress
{ "answer_score": -1, "question_score": 0, "tags": "php, advanced custom fields, variables" }
How (or where) do I get wordpress plugin update download link? When I update a plugin, that isn't hosted on the repository, I often wonder "Where is the updated plugin being downloaded from?". Any idear on how would I go about find out the update link?
The latest plugin update information is available by `print_r(get_site_transient('update_plugins'));` or if you want to filter out wordpress.org plugins and make it more readable... $pluginupdates = get_site_transient('update_plugins'); foreach ($pluginupdates->response as $pluginupdate => $values) { if (!stristr($values->package,'wordpress.org')) { echo "Plugin Name: ".$values->slug." --- "; echo "Update Package: ".$values->package."<br>".PHP_EOL; } } Of course, this will just return blank if there are none, and will not list updates not do not use the WordPress Plugin API for Updates (plugins not using the wordpress.org repository are also likely to use their own update mechanism.) For plugins that do not have a current update available, it is going to vary from plugin to plugin, you may have to find it in the plugin code on an individual basis.
stackexchange-wordpress
{ "answer_score": 1, "question_score": 0, "tags": "plugins, updates, options, automatic updates" }
wp rest api v2 return json_no_route i am using WP rest API v1 and everything is ok. But now i want taste some WP rest API v2. the problem is, when i cal: > mysite.com/wp-json/wp/v2/posts or: > mysite.com/wp-json/wp/v2/post or > mysite.com/wp-json/wp/v2/posts/ or any thing else is related ti this path: > mysite.com/wp-json/wp/v2... the result is: [{"code":"json_no_route","message":"\u0647\u06cc\u0686 \u0645\u0633\u06cc\u0631 \u062a\u0637\u0628\u06cc\u0642 URL \u0648 \u0631\u0648\u0634 \u062f\u0631\u062e\u0648\u0627\u0633\u062a \u067e\u06cc\u062f\u0627 \u0634\u062f"}] and i don't know what is the problem and the point is i want to use WP rest API v1 and v2, together, so disabling WP rest API v1 is not an option. PS: I removed and add WP rest API v2 but nothing change.
OK, i find my answer. Just ask it here and as dear Charles sayed, they answered me, so fast, the answer is: > By default, WP-API v1 takes priority over v2. If v1 is installed and activated, then v2 routes are inaccessible. > > To mitigate this, you'll need to register either v1 or v2 to a different base than wp-json. Both have filters to make this more or less easily possible: add_filter( 'rest_url_prefix', function() { return 'wp-api'; }); and because i am not a WordPress guy, so i don't know where should i add this lines so i get help from this blog and add the lines to the > function.php of my them.
stackexchange-wordpress
{ "answer_score": 5, "question_score": 5, "tags": "wp api, rest api" }
WooCommerce add_action hook results in 500 error I am trying to add a line of text on the checkout page of the store that will go immediately after shipping row. I added the following to my child theme functions.php file: add_action( 'woocommerce_review_order_after_shipping', 'action_woocommerce_review_order_after_shipping'); function action_woocommerce_review_order_after_shipping( ) { echo = "<p>Text Goes Here</p>"; }; For some reason it leads to a 500 error. Any idea what I am doing wrong?
Remove the `=` sign after your `echo` statement... `echo = "<p>Text Goes Here</p>";` ...becomes `echo "<p>Text Goes Here</p>";` Final add_action( 'woocommerce_review_order_after_shipping', 'action_woocommerce_review_order_after_shipping'); function action_woocommerce_review_order_after_shipping( ) { echo "<p>Text Goes Here</p>"; }
stackexchange-wordpress
{ "answer_score": 5, "question_score": 2, "tags": "functions, hooks, actions" }
How can I get a list of users by their role? How can I get a list of all users that are in WordPress by their role or capabilities? For example: * Display `all subscribers list` in WordPress. * Display `all authors list` in WordPress. * Display `all editors list` in WordPress.
There may be some different way to do that, but most proper way to do that is following. <?php $args = array( 'role' => 'Your desired role goes here.', 'orderby' => 'user_nicename', 'order' => 'ASC' ); $users = get_users( $args ); echo '<ul>'; foreach ( $users as $user ) { echo '<li>' . esc_html( $user->display_name ) . '[' . esc_html( $user->user_email ) . ']</li>'; } echo '</ul>'; ?>
stackexchange-wordpress
{ "answer_score": 32, "question_score": 17, "tags": "user roles, capabilities" }
how to add acf value to other plugins shortcode? Hi I am creating site with ACF and other plugin (WP-Appbox). WP-Appbox allow me to add little download box of app with shortcode. shortcode is as follow. [appbox storename appid]. If I want to show chrome from google store I will add [appbox googleplay com.android.chrome] in post or theme. so my requirement is how can I manipulate storename value and app id. with advanced custom field. ex. there will be 2 acf field store-name and app-id so I can add those field values from editor to shortcode. and following code is added in single.php as of now I came to this. $thestore = get_field('store-name'); $theapp = get_field('app-id'); echo do_shortcode("[appbox $thestore $theapp]"); but its not working.
try adding quotes around the values returned by ACF: $thestore = get_field('store-name'); $theapp = get_field('app-id'); echo do_shortcode('[appbox "' . $thestore . '" "' . $theapp . '"]');
stackexchange-wordpress
{ "answer_score": 0, "question_score": 0, "tags": "shortcode, advanced custom fields" }
Plugin upgrade failing during unzip I am having an issue upgrading one particular plugin on a site of mine. All other plugins on this site upgrade without an issue. It is not a permissions issue as this has been checked multiple times and like I say all other plugins update perfectly. The error occurs during the unzipping of the upgrade package. Specifically it occurs in the `_unzip_file_ziparchive` function. The error is sometimes mkdir_failed_ziparchive (Could not create directory) and other times it is copy_failed_ziparchive (Could not copy file). The directory or file on which it fails varies. It is not the first directory it tries to create or the first file it tries to copy. I have run the process with some logging code added and can see that it is able to create many directories/copy many files to the location in the wp-content/upgrade folder before throwing the error. I am stumped as to what the cause could be and would appreciate any insights.
The name of the temporary file created by the `download_url` function is 118 characters long. The length of this is causing the full path name of some files or directories created during the unzip process to be longer than the allowable length on Windows. Therefore an error is thrown and the plugin upgrade fails. I have added details to the thread at <
stackexchange-wordpress
{ "answer_score": 1, "question_score": 0, "tags": "plugins, errors, updates, upgrade" }
Why the post ID is 0 in a hook within wp_insert_post_data? I am having trouble getting the ID of the post in a function applied to the `wp_insert_post_data` filter. It is actually zero. To clarify I am getting the `$postarr` and the value of the `ID` field is 0. (meaning number of parameters is correct, 2, in the `add_filter` declaration) What can cause this?
As deduced from the comments, and the source code, the `ID` for new posts is only generated after the hook `wp_insert_post_data`, the wordpress codex is misleading in this regard.
stackexchange-wordpress
{ "answer_score": 0, "question_score": 0, "tags": "hooks" }
Conditional to test if post has password protection enabled I am looking for a conditional to test simply if a post (custom post type, if it somehow makes a difference) is set to have password protection…persistently…regardless of whether user has accessed the post via the password or not. `post_password_required()` only returns true if the user has not already entered the password `get_post_status()` (though it _does_ return a 'private' status if a post is private) only returns 'published' for a password-protected post
You could use if(!empty($post->post_password)){ // do some stuff } which is what the post_password_required() code does before checking the user's credentials against the password itself.
stackexchange-wordpress
{ "answer_score": 8, "question_score": 6, "tags": "password" }
Can't make product images clickable I've tried many things and many solutions but i can't make product images clickable. Here's the code: if ( has_post_thumbnail() ) { $images .= get_the_post_thumbnail( $post->ID, 'shop_catalog' ); } If i make the code look like this, it doesn't show images: return '<a href="' . get_permalink( $post->ID ) . '">' . get_the_post_thumbnail( $post->ID, 'shop_catalog' ) . '</a>';
try this.. $images .= '<a href="' . get_permalink( $post->ID ) . '">'; if ( has_post_thumbnail() ) { $images .= get_the_post_thumbnail( $post->ID, 'shop_catalog' ); } $images .= '</a>';
stackexchange-wordpress
{ "answer_score": 0, "question_score": 0, "tags": "php, woocommerce offtopic, html" }
WP-all-import problems with large input file I'm running development environment xampp (windows) and production server. On the DEV virtual machine, everything works correctly, PROD server doesn't work: * wp-all-import plugin * large XML feed < (175 MB) * login to wp wp-all-import -> new import -> from URL * file correctly downloaded to server -> AJAX redirect to "xpath builder" -> xpath "/PRODUCT" AJAX returns only 15 results * no NOTICE/WARNING/ERROR in php log * DEV machine imports all 82600 records correctly I tried to find php config differences, but memory limit, script exec time etc. are the same... dev machine is PHP 5.4, production PHP 5.3 (but newer version of libxml than in dev)... Any idea, what could possibly cause the problem? Thanks
wrong source file encoding (not utf8 as xml prolog claims), wp-all-import wordpress plugin hid the php error
stackexchange-wordpress
{ "answer_score": 0, "question_score": -2, "tags": "import, xml" }
WooCommerce pages accessible to logged in members only I’m building a shop in WooCommerce and wish to restrict access & viewing of the shop to logged in members only. I don’t mind having links to the shop visible (such as in the nav bar), as clicking the shop link, or trying to directly access a shop item would check if the user is logged in, and if not, then redirected to ‘My Account’ to create an account. Any there any options available to me via plugins or the functions.php? Secondly, I found an answer the thread below, which is almost exactly what I want: Make WooCommerce pages accessible for logged in users only I made the suggested changes, but I got an error. Would the error be that I have to insert information unique to my WP install in the following line: add_action(‘template_redirect’, ‘wpse_131562_redirect’);
I just tested this and it will work. Drop this into your functions.php and whenever a user who isn't logged in tries to access a WooCommerce template such as the shop, product pages, cart, or checkout it will redirect them to the WordPress login page. add_action( 'template_redirect', 'redirect_users_not_logged_in' ); /** * Redirect non logged-in users to login page when they try to access any * woocommerce template including the cart or checkout page. * * @author Joe Dooley - Developing Designs * @return void * */ function redirect_users_not_logged_in() { if ( ! is_user_logged_in() && ( is_woocommerce() || is_cart() || is_checkout() ) ) { auth_redirect(); exit; } }
stackexchange-wordpress
{ "answer_score": 2, "question_score": 2, "tags": "woocommerce offtopic" }
how to get nonce using json api I try to open this url in my browser or calling from my frontend application: i keep getting the response `{"status":"error","error":"Include 'controller' and 'method' vars in your request."}` what is wrong, I want to be able to create a custom post type with custom fields in the end but using json api I need nonce first
You need to call like below. **API call:-** **Responce:-** {"status":"ok","controller":"posts","method":"create_post","nonce":"92f31d49b5"}
stackexchange-wordpress
{ "answer_score": 4, "question_score": 2, "tags": "api, nonce, plugin json api" }
Limit access to a page I try to limit access to a page only for registered users before a specific date. For the others, a message must be display. Here is my code <?php if( strtotime( $user->user_registered ) < mktime( 0, 0, 0, 3, 7, 2016 ) ) { echo do_shortcode('[gravityform id=14]'); } else { echo "Désolé. La participation est réservée aux membres inscrits avant le 07 mars 2016."; } ?> Actually, this code display the gravityform even if registration date is taller than mktime value. I want to display the message "Désolé. La participation est réservée aux membres inscrits avant le 07 mars 2016." for users registered after 2616/03/06. How can i do it ? Thanks for your help.
Find by myself. Just forget to declare `$user = wp_get_current_user();`
stackexchange-wordpress
{ "answer_score": -1, "question_score": 0, "tags": "date, user registration, limit" }
Change post title if post has specific category Basically what I am trying to achieve is to have title changed of posts which are in category number 30. My code is: function adddd($title) { if(has_category('30',$post->ID)){ $title = 'Prefix '.$title; } return $title; } add_action('the_title','adddd'); The code works, but has one issue. When I am inside the post which has that category, title is being changed for all other pages (which are called through the_title) too. How can I change the title only to post titles which has that category, no matter what page I am on?
`$post` is undefined in your filter. You need to explicitely invoke the `$post` global inside your filter function to have it available. You must remember that variables ( _even global variables_ ) outside a function will not be available inside a function, that is how PHP works. You actually do not need to use the `$post` global, the post ID is passed by reference as second parameter to the `the_title` filter. You can use the following: add_action( 'the_title', 'adddd', 10, 2 ); function adddd( $title, $post_id ) { if( has_category( 30, $post_id ) ) { $title = 'Prefix ' . $title; } return $title; } If you need to target only the titles of posts in the main query/loop, you can wrap your contional in an extra `in_the_loop()` condition
stackexchange-wordpress
{ "answer_score": 1, "question_score": 0, "tags": "categories, filters, get the title" }
How to run JavaScript function in WooCommerce checkout? I'm building reCAPATCHA into my WooCommerce checkout. It is a fairly easy process as I'm using `woocommerce_checkout_process` to validate the capatcha. However, I have running into one issue. When there is a cart error, I want to be able to reset the reCAPATCHA using `grecaptcha.reset();` JavaScript function. I'm unsure how to run the JavaScript command upon cart error in WooCommerce. Any tips? Thanks!
I have not been able to figure out how to inject JavaScript upon cart error. However, I am using a workaround -- `setInterval` at WooCommerce checkout that looks for an error message, and then calls `grecaptcha.reset();`
stackexchange-wordpress
{ "answer_score": 1, "question_score": 1, "tags": "javascript, woocommerce offtopic, captcha" }
How to get the first image gallery of a product in woocommerce in a loop I want to display a product with a product image and when visitor hovers over that image, it will change to the first image from the product gallery. I am using this code to display the image gallery, but it displays all the images from product gallery. I just want the 1 image. <?php do_action( 'woocommerce_product_thumbnails' ); ?> Anybody know how to resolve this problem? Really appreciate any ideas. Regards
Along with the product thumbnail (I'm assuming you have this), what you need is a list (array) of the product images - WooCommerce has such methods, eg `$product->get_gallery_attachment_ids()`. You can grab the first ID in the array and use it to fetch the single image using `wp_get_attachment_image()`, or `wp_get_attachment_url()`, etc., then use that as an alternate source for the main (thumbnail) image. Incidentally, the `woocommerce_product_thumbnails` call is outputting markup that you probably don't want to use. You'll need to either discard this or unhook functions from it to get the output you want.
stackexchange-wordpress
{ "answer_score": 3, "question_score": 4, "tags": "loop, woocommerce offtopic, gallery" }
Wordpress CPT slug and page slug conflicts I have one page slug "new-site" also i have another custom post type with same slug "new-site" while i browse site < then it directally goes to archive page and show all the posts from CPT new site. How can i solve if i open with this url to page < and < for cpt post detail. Thanks
As you don't need the CPT archvie, the easiest way to use `example.com/new-site` to open a page, and `example.com/new-site/post-slug` to open single posts of "new-site" post type, is to declare `has_archive => false` when registering the CPT: add_action( 'init', 'cyb_register_cpt' ); function cyb_register_cpt() { $args = array( // ..... 'has_archive' => false ); register_post_type( 'new-site', $args ); } PD: Remember to flush the rewrite rules: add_action( 'init', 'cyb_register_cpt' ); function cyb_register_cpt() { $args = array( // ..... 'has_archive' => false ); register_post_type( 'new-site', $args ); } register_activation_hook( __FILE__, function () { cyb_register_cpt(); flush_rewrite_rules(); } ); register_deactivation_hook( __FILE__, function () { flush_rewrite_rules(); } );
stackexchange-wordpress
{ "answer_score": 2, "question_score": 0, "tags": "rewrite rules, slug" }
Can I use both a custom excerpt and a trimmed excerpt? For each post, I use the custom excerpt field to write a custom excerpt (180 characters max) for each of my posts, which I use as the meta description of my post for SEO. When I show a list of my posts (archive pages, categories etc.) this excerpt is displayed as "teaser text" for each of my posts. The problem is that this text is too short, as it is written for meta description purposes. Would it be possible to have a longer excerpt showing in category and index pages, yet keep my custom excerpt as a meta description of each post? Btw, most of my posts have a specifically placed "read more" tag, which now is ignored as I have a custom excerpt.
We can try to filter the excerpt through the `get_the_excerpt` filter. By default, if we have a manual excerpt, the manual excerpt will be used and not the automatically created excerpt which is created by the `wp_trim_excerpt()` function. We can alter this behavior. What we will do is, when we are inside the main query ( _`in_the_loop()`_ ), we will return the output from the `wp_trim_excerpt()` function. This way, we keep all filters as per default. Whenever we are outside the main query, we can return the manually created excerpt, if it exists, otherwise the normal excerpt add_filter( 'get_the_excerpt', function( $text ) { if ( in_the_loop() ) return wp_trim_excerpt(); return $text; });
stackexchange-wordpress
{ "answer_score": 3, "question_score": 1, "tags": "loop, excerpt" }
Is define('WP_CACHE', true) needed for object caching? I am just reading the docs at < and am not clear on something... If I install an object cache plugin by adding the drop-in file _object-cache.php_ to the _wp-content_ directory do I need to add `define('WP_CACHE', true)` to my _wp-config.php_ file to activate caching or will the drop-in file just start interacting with the cache by its mere presence?
No, including this constant with a value of TRUE loads advanced-cache.php. Object-cache.php is loaded and used automatically. See <
stackexchange-wordpress
{ "answer_score": 7, "question_score": 14, "tags": "cache" }
Check if widget has content I just need to check, if sidebar has any content My `functions.php`code is below. function aspirationas_extra_widget_1_init() { register_sidebar(array( 'name' => __('Extra Widget 1', 'aspirations'), 'id' => 'extra_widget_1', 'description' => __('Widgets for Extra 1', 'aspirations'), 'before_widget' => '<aside>', 'after_widget' => '</aside>', 'before_title' => '<h3>', 'after_title' => '</h3>', )); } add_action('widgets_init', 'aspirationas_extra_widget_1_init'); And I read this widget by this code below. dynamic_sidebar('extra_widget_1'); I am beginner in wordpress development. I know this is a sili question, but I can not solved it. any one help me please.
Problem solved by this code below: <?php if (is_active_sidebar('extra_widget_1')) { ?> <li> <?php dynamic_sidebar('extra_widget_1'); ?> </li> <?php } ?>
stackexchange-wordpress
{ "answer_score": 2, "question_score": 3, "tags": "php, widgets" }
Help with rewrite rules for two post types I'm trying to setup two rewrite rules for two post types. Basically, the structure I want is this: `site.com/app/course/xxxx/` => adds query_var _course_ `site.com/app/course/xxxx/theme/xxxx/` => adss query vars _course_ and _theme_ I set up two `add_rewrite_rule`: public function rewrite_rules(){ add_rewrite_tag( '%course%', '([^&]+)' ); add_rewrite_tag( '%theme%', '([^&]+)' ); add_rewrite_rule("^app/course/([^/]+)/?",'index.php?page_id=3400&course=matches[1]', 'top' ); add_rewrite_rule('^app/course/([^/]+)/theme/([^/]+)/?','index.php?page_id=3400&course=$matches[1]&theme=$matches[2]', 'top' ); } If I add just the first rule, it works. If I only add the second rule, it works too. But, if I add both, only the first rule works. The second rule loads a valid page, but the _theme_ var is not set. Am I doing something wrong? Any tips are welcome!
The first rule is capturing all requests. If you add a `$` anchor at the end of the rules, they'll behave as expected (you could also just switch the order of the rules so the more specific one "wins"). add_rewrite_rule( '^app/course/([^/]+)/?$', 'index.php?page_id=3400&course=matches[1]', 'top' ); add_rewrite_rule( '^app/course/([^/]+)/theme/([^/]+)/?$', 'index.php?page_id=3400&course=$matches[1]&theme=$matches[2]', 'top' ); Check out Monkeyman Rewrite Analyzer for debugging rules. Also note that `theme` is used by WordPress internally as a POST or GET var, I suggest changing that to something unique to prevent any potential conflict.
stackexchange-wordpress
{ "answer_score": 0, "question_score": 1, "tags": "url rewriting, rewrite rules, rewrite tag" }
Debugging 'Object of class WP_Query could not be converted to int' error I am seeing the PHP notice error; Notice: Object of class WP_Query could not be converted to int in G:\.....\property-search-form.php on line 350 At that line I have a meta query that create a new WP_Query set of results using the code; $results = new WP_Query( $args ); if(($results == 0) || ($results == false) || ($results == NULL) || !is_object($results) || !($results->have_posts())) { return $results; } else { return $results; } I understand that the final $result is a number, when I ran it with 9 matching results and used print_r to display the results it returns 9, so not sure what this error means, and how to resolve it.
The issue if that your conditional is trying to convert an Object into things that it cannot be converted to. WP_Query returns a WP_Query Object so when it's tested against `Object == 0` \- it tries to convert the object into a number during the comparison but cannot. You instead need to test against `$results->have_posts()` or one of it's properties such as `0 === $results->found_posts`
stackexchange-wordpress
{ "answer_score": 5, "question_score": 3, "tags": "errors" }
The permalink for the page doesn't work and page's defined link throws "Object not found!" I created new page in a fresh WordPress install. Version of WordPress is fairly new - 4.4.2. I set the permalink for the new page to be `
Check your permalinks in settings dubmenu item in wordpress's admin. Check so it is set properly and .htaccess is set properly. If it isn't try copy and paste the suggested content of it to the actual .htaccess file and try again.
stackexchange-wordpress
{ "answer_score": 0, "question_score": 0, "tags": "permalinks, pages" }
Free theme and css/bootstrap.css is not overridden in the child theme Why is wordpress still using the bootstrap.css from the parent theme, whenI have a child theme which (successfuly for other things) inherits the parent theme? I have the bootstrap.css settled in the child theme inside the same directory css/ and I can see in firebug that on the page the parent's bootstrap.css is still used.
you need to enqueue styles in child theme's function.php to override parents styles. if you want to completely removed parent's bootstrap css then use wp_dequeue_styles() function and enqueue new bootstrap css in child theme's function.php <
stackexchange-wordpress
{ "answer_score": 1, "question_score": 0, "tags": "css, child theme, parent theme" }
Custom button on custom taxonomy listing page I want to have a custom button at custom taxonomy listing page. Please see the screenshot, I need a button so that I can export all my terms. ![enter image description here]( I am not able to find any hook to do something like that. Hook I have tried is `admin_footer,` but it's used for any javascript type of work.
This action hook (found in `/wp-admin/edit-tags.php`) will output the button _below_ the table (not _quite_ where you have asked to position it, but it is an easily available action and outside the `form` table.) $taxonomy = 'location'; // you will probably need to change this add_action('after-{$taxonomy}-table','custom_export_button'); function custom_export_button($taxonomy) { $export_url = admin_url('admin-ajax.php').'?action=export_taxonomy'; echo "<form action='".$export_url."' method='post'>"; echo "<input type='hidden' name='taxonomy' value='".$taxonomy."'>"; echo "<input type='submit' value='EXPORT'></form>"; } add_action('wp_ajax_export_taxonomy','custom_export_taxonomy'); function custom_export_taxonomy() { // YOUR CUSTOM TAXONOMY EXPORT FUNCTION }
stackexchange-wordpress
{ "answer_score": 0, "question_score": 0, "tags": "custom taxonomy, hooks, buttons" }
How to dequeue / deregister parent theme style I'm making a child theme, and I'd like to remove the Google font style that it calls for in 'fonts-style' function nada_theme_styles() { wp_register_style( 'fonts-style', '//fonts.googleapis.com/css?family=Roboto:300,700', array(), null, null ); wp_register_style( 'nada-style', get_stylesheet_uri() ); wp_enqueue_style( 'fonts-style' ); wp_enqueue_style( 'nada-style' ); } add_action('wp_enqueue_scripts', 'nada_theme_styles'); I currently have this: function remove_nada_theme_font_style() { wp_deregister_style( 'fonts-style' ); wp_dequeue_style( 'fonts-style' ); } add_action( 'wp_enqueue_scripts', 'remove_nada_theme_font_style' ); I've tried that as well as adding my action to wp_print_scripts and styles, and changing the priority. I've referenced similar threads here, and I'm not sure what I'm missing. Thanks for your help!
It is pretty simple: function remove_nada_theme_font_style() { remove_action( 'wp_enqueue_scripts', 'nada_theme_styles' ); } add_action( 'after_setup_theme', 'remove_nada_theme_font_style' ); Since the child theme is loaded before the parent theme, you can't simply remove the action. because the add_action calls in the parent theme will simply overwrite your requests. You have to wrap it into the after_setup_theme hook. This hook will fire after the child and parent theme is loaded. So all removing filters and actions from the parent theme should go there. Source: < **edit** This will remove the whole styles and not just the font scripts. If you just want to deregister the font: function remove_nada_theme_font_style() { wp_dequeue_style( 'fonts-style' ); wp_deregister_style( 'fonts-style' ); } add_action( 'after_setup_theme', 'remove_nada_theme_font_style' );
stackexchange-wordpress
{ "answer_score": 2, "question_score": 0, "tags": "wp enqueue script, child theme, wp enqueue style, parent theme" }
How to remove only images from the_content() When I call the_content(), I want to show only text and don't want to show images. Notable that, I don't want to remove text style. The text style should be display as well. How can I do this?
This answer already here How to remove images from showing in a post with the_content()? <?php $content = get_the_content(); $content = preg_replace("/<img[^>]+\>/i", " ", $content); $content = apply_filters('the_content', $content); $content = str_replace(']]>', ']]>', $content); echo $content; ?>
stackexchange-wordpress
{ "answer_score": 3, "question_score": -2, "tags": "the content" }
Fatal error Call to a member function filter() I am using wordPress version 4.4.2 + Jupiter 5.08 on Apache 2.2.22 (Debian) The website seems to be fully operational, but in the Apache error log I got this message : > PHP Fatal error: Call to a member function filter() on a non-object in wp-includes/taxonomy.php on line 805 This is the concerned line: // Sanitize term, according to the specified filter. $_term->filter( $filter ); I made some test to fix it ( _like trying to dump`$_term`_) without success. Only skipping the instruction would stop the error, but i don't think that would be the good solution.
Some entries has been deleted in the table `wp_term_taxonomy` causing this trouble. Database has been rollback before thoose changes and now it works.
stackexchange-wordpress
{ "answer_score": 0, "question_score": 0, "tags": "taxonomy" }
JSON API plugin, Get posts by category return no post Im trying to get the posts by category. using this URL: /api/core/get_category_posts/?slug=cat2 But responding this: {"status":"ok","count":0,"pages":0,"category":{"id":3,"slug":"cat2","title":"Cat2","description":"","parent":0,"post_count":7},"posts":[]} Posts are empty! any idea?
get_category_posts/?slug=cat1&post_type=project I forgot to set post_type.
stackexchange-wordpress
{ "answer_score": 1, "question_score": 1, "tags": "json, categories, plugin json api" }
Pages should have priority when using add_rewrite_rule I'm using the following code to have dynamic pages function custom_rewrite_basic() { add_rewrite_rule('^prefix-(.*)', 'foo/bar/index.php?page=$matces[1]', 'top'); } add_action('init', 'custom_rewrite_basic'); This catches `/prefix-*` pages and serves my `index.php` file. For example: `/prefix-foo` serves `foo/bar/index.php?page=foo`. If I add a new page with the url `/prefix-foo`, I want it to have priority (to serve the content from the database, not from my PHP file). How can I do that without changing the regex?
If I understand you correctly, you could try to replace: add_rewrite_rule( '^prefix-(.*)', 'foo/bar/index.php?page=$matces[1]', 'top' ); with add_rewrite_rule( '^prefix-(.*)', 'foo/bar/index.php?page=$matces[1]', 'bottom' ); From the Codex: > '`top`' will take precedence over WordPress's existing rules, where '`bottom`' will check all other rules match first. Default: "`bottom`"
stackexchange-wordpress
{ "answer_score": 4, "question_score": 2, "tags": "functions, pages, rewrite rules" }
What is the correct workflow for modifying child themes? I am asking the following because I am fairly new to WordPress. I want to change the fontsize for post titles. This is what I do: 1. I inspect a post title in Chrome using _devtools_ , and find out the style used. 2. I edit _style.css_ in the child theme and place the modified fontsize into the style definition used for post titles. Is this how it's done? If not, what is the accepted methodology?
What you are doing is correct. Any changes like the ones you are doing should go into a child theme or a custom plugin. Since we are talking about CSS, which is very theme specific, changes should go into a child theme ## EDIT From comments, and credit to @birgire, > ( _styles are_ ) sometimes handled by the theme itself via the theme customiser or theme options To answer the other comment, the dev tools on browsers are excellent tools to inspect elements in order to know how that specific element is displayed. This will not only tell you the specific color/font size etc the element is using, but also the HTML tag which wraps that element and the particular class/id of that specific tag
stackexchange-wordpress
{ "answer_score": 2, "question_score": 0, "tags": "child theme, css" }
Difference between how to set path to the theme folder I crate many wordpress based sites. When i need to include path to the theme folder, i use this code `<?php bloginfo('template_url'); ?>`. I`m **Theme check** plugin. And they say to me > bloginfo('template_url') was found in the file services-section.php. Use echo esc_url( get_template_directory_uri() ) instead. What the difference between this to methods? Which is better to use?
> **‘template_url‘ / ‘template_directory‘** – URL of the active theme’s directory. Within child themes, both get_bloginfo(‘template_url’) and get_template() will return the parent theme directory. Consider echoing get_template_directory_uri() instead (for the parent template directory) or get_stylesheet_directory_uri() (for the child template directory). Source: < the function `get_template_directory_uri()` is the better one, if you want to support creating child themes. if you don't care, it shouldn't matter much. **edit:** did a simple speed test and found no significant difference: blog_info('template_url') 0.00010 sec get_template_directory_uri() 0.00007-0.00010 sec
stackexchange-wordpress
{ "answer_score": 0, "question_score": 0, "tags": "paths" }
translate_user_role doesn't work I did dozens of tests, this is the code that I am tring to make work: $user = get_userdata($user_ID); /* WE NEED TO REMOVE BBP ROLES */ $roles = array(); global $wp_roles; foreach ($user->roles as $key => $role) { if (substr($role, 0, 4) != 'bbp_') { array_push($roles, translate_user_role($wp_roles->role_names[$role])); } } I replaced the parameter passed to translate_user_role with a lot of others but nothing works, neither just: translate_user_role('Administrator'); or translate_user_role('administrator');
Please note that `translate_user_role` doesn't work in the front-end currently. Here is a workaround, you can place this in your theme: add_action( 'init', 'load_admin_textdomain_in_front' ) function load_admin_textdomain_in_front() { if ( ! is_admin() ) { load_textdomain( 'default', WP_LANG_DIR . '/admin-' . get_locale() . '.mo' ); } }
stackexchange-wordpress
{ "answer_score": 0, "question_score": 0, "tags": "user roles, translation, localization" }
Is there a way to remove the default css from TinyMCE? I'm working on getting the editor to look more like the front end by adding extra CSS to the TinyMCE rich text editor. WordPress adds `/wp-includes/js/tinymce/skins/lightgray/content.min.css` and `/wp-includes/js/tinymce/skins/wordpress/wp-content.css` by default. Is there an easy way to remove this?
This is what I arrived at. This will remove just the custom wordpress css `/wp-includes/js/tinymce/skins/wordpress/wp-content.css`. function squarecandy_tinymce_remove_mce_css($stylesheets) { $stylesheets = explode(',',$stylesheets); foreach ($stylesheets as $key => $sheet) { if (preg_match('/wp\-includes/',$sheet)) { unset($stylesheets[$key]); } } $stylesheets = implode(',',$stylesheets); return $stylesheets; } add_filter("mce_css", "squarecandy_tinymce_remove_mce_css"); The other file loaded by default (`/wp-includes/js/tinymce/skins/lightgray/content.min.css`) is not part of the mce_css filter. There does not appear to be any way to remove this without breaking TinyMCE. But of the two css files, this one adds less default things that need to be overridden.
stackexchange-wordpress
{ "answer_score": 2, "question_score": 1, "tags": "tinymce, admin ui" }
How Can Hide Define Category in Post Contents? This is My Category List : 1- Years 2- Genere And I use This Code For show in posts : <?php the_category(' , ') ?> How Can Hide "Year or Genere" in up code? Please Help Me.i want Show Only One Category.
First add `get_the_categories` filter before `the_category(' , ')` then remove it. So it will not effect categories on other places. add_filter( 'get_the_categories', 'remove_selected_categories' ); the_category(' , '); remove_filter( 'get_the_categories', 'remove_selected_categories' ); In callback function check for categories to remove then remove them! function remove_selected_categories( $categories ) { $categories_to_remove = array( 'years', 'genere' ); //Place the slug for categories foreach ($categories as $index => $single_cat) { if (in_array($single_cat->slug, $categories_to_remove)) { unset($categories[$index]); } } return $categories; } Check the documentation for get_the_categories filter.
stackexchange-wordpress
{ "answer_score": 0, "question_score": 0, "tags": "categories, list" }
Correct use of get_the_terms() I need to print all terms associated to a custom post type post. In the post template I wrote that code: <?php foreach (get_the_terms(the_ID(), 'taxonomy') as $cat) : ?> <?php echo $cat->name; ?> <?php endforeach; ?> The loop works correctly, but before the list also the id was printed. Like: 37 taxonomy01 taxonomy02 taxonomy03 What is wrong?
`the_ID()` print the post ID. You need to use the `get_the_ID()` which return the post ID. Example: foreach (get_the_terms(get_the_ID(), 'taxonomy') as $cat) { echo $cat->name; } Always remember the naming convention of WordPress for template tags. `the` which mean to print `get` which mean to return in most of the cases.
stackexchange-wordpress
{ "answer_score": 11, "question_score": 4, "tags": "terms" }
Wp Rest Api Custom Endpoint for page subpages I'm tring to add a custom endpoint for a page subpages. Parent Page ID = 151 function list_subpages( $data ) { $subpages = get_pages( array( 'child_of' => $data['151'], ) ); if ( empty( $subpages ) ) { return null; } return $subpages; } add_action('rest_api_init', function () { $version = '2'; $namespace = 'wp/v' . $version; $base = 'subpagelist'; register_rest_route($namespace, '/' . $base, array( 'methods' => 'GET', 'callback' => array($this, 'list_subpages'), )); }); Getting status 500 error.. How can I fix it?
It works.. function list_subpages() { $data = array(); $request = array(); $id = 151; $subpages = get_pages( array( 'child_of' => $id, 'sort_column' => 'menu_order' ) ); if ( empty( $subpages ) ) { return null; } foreach ($subpages as $p) { $data['id'] = $p->ID; $data['title'] = $p->post_title; $data['img'] = wp_get_attachment_url( get_post_thumbnail_id($p->ID) ); $request[] = $data; } return new WP_REST_Response($request, 200); } add_action('rest_api_init', function () { $namespace = 'wp/v2'; $base = 'hizmetler'; register_rest_route($namespace, '/' . $base, array( 'methods' => 'GET', 'callback' => 'list_subpages', )); });
stackexchange-wordpress
{ "answer_score": 2, "question_score": 2, "tags": "rest api" }
How to use WP Theme Option: Custom_Backgrounds on specific element? I want to use the WP Theme option Custom_Backgrounds on a specific div. By default it adds it to the body and I dont see a way of changing this. Does anyone know how?
If your theme uses in-built `custom-background` callback then you can overwrite `add_theme_support` in your child theme. Yo do not need to use `remove_theme_support`. First add `custom-background` support with your callback function. $defaults_args = array( 'wp-head-callback' => 'my_custom_background_cb', ); add_theme_support( 'custom-background', $defaults_args ); In callback function specify `div` CSS class or ID function my_custom_background_cb() { $bg_image = get_background_image(); if ( empty( $bg_image ) ) { return; } else { ?> <style type="text/css"> .your-div-class { background: url('<?php echo $bg_image; ?>') no-repeat; } </style><?php } } If theme printing CSS in header or using some other custom function (not using callback function) then you can remove body background image by CSS.
stackexchange-wordpress
{ "answer_score": 1, "question_score": 0, "tags": "theme options, theme customizer, custom background" }
Logging in takes a few refreshes to show you are logged in, is this a cache issue? This error has plagued me for years, when you login to the website via the buddypress widget on the right, or via the direct wp-login.php even if its successful, the page you are on when you logged in is not updated to show you logged in successfully, sometimes if you visit another page it'll show you as logged in, sometimes you have to login a good 3-10 times for it to actually show you are logged in! Is this a cache issue? Theme or plugin issue? I use Buddypress, BBPress, Totalcache and were pushing through cloudflare. I have a lot of security plugin that could also be conflicting: Akismet, Bad Behavior, WangGuard, Wordfence Security. < This community seems to be mostly development but the description says administrators are welcome, and my post has been ignored on the wordpress forums for 4 months now.
Figured it out; it was W3 Total Cache; removed this and no login issues.
stackexchange-wordpress
{ "answer_score": -1, "question_score": 0, "tags": "login, wp login form" }
How to change the location of admin notice in html without using Javascript? I am adding an admin notice via the conventional `admin_notice` hook in my plugin: function my_admin_notice() { ?> <div class="notice notice-info is-dismissible"> <p><?php _e( 'some message', 'my-text-domain' ); ?></p> </div> <?php } if ( my_plugin_show_admin_notice() ) add_action( 'admin_notices', 'my_admin_notice' ); How can I control where wordpress places the admin notice, in the html on the current screen, without using Javascript?
I found out by accident recently that all the notices will be moved to after the first `<h2>` tag on the page inside a `<div class="wrap">`. This gives you some _slight_ control in that, for example, on a plugin settings page you can put an empty `<h2></h2>` at the very top if you want to use `<h2>Plugin Title</h2>` without it messing up the display formatting there.
stackexchange-wordpress
{ "answer_score": 10, "question_score": 1, "tags": "hooks, notices" }
How to change _wp_attachment_metadata specific value in SQL? i had to resize a lot of existing images in my upload folder (around 1k). After reuploading them, Wordpress of course, doesn't recognize the new dimensions. My approach was to just change the size in the _post_meta table. But this looks like this: a:6{s:5:"width";s:3:"330";s:6:"height";s:4:"1067";s:14:"hwstring_small";s:22:"height='96' width='29'";s:4:"file";s:22:"2012/03/2-IMG_1540.png";s:5:"sizes";a:3:{s:9:"thumbnail";a:3:{s:4:"file";s:21:"2-IMG_1540-56x183.png"; ... All I need to change is the "width" value of the first entry from "330" to sth. else. Although it looks like a dictionary to me I do not find a way to get access to that value in SQL. The wp_update_attachment_metadata reference states that all data must be given as existing data will be wiped. That's the reason why I thought it would be easier to do it in SQL.
You could do this via PHP instead of SQL, just get the existing metadata and change what you need to, it will handle the serializing for you: $newwidth = '250'; // or whatever it is $attachments = get_posts(array('post_type'=>'attachment')); foreach ($attachments as $attachment) { $id = $attachment->ID; $metadata = wp_get_attachment_metadata($id); $metadata['width'] = $newwidth; wp_update_attachment_metadata($id,$metadata); } But really, you may do better using the Regenerate Thumbnails Plugin which may fix this and regenerate the different thumbnail sizes at the same time.
stackexchange-wordpress
{ "answer_score": 1, "question_score": 2, "tags": "post thumbnails, attachments, images" }
Correct use of curly braces vs alternative synax In most themes I've looked at and WordPress core, I'm seeing the use of `endwhile` and `endif`. Is there a good reason why WordPress uses these instead of curly braces for block statements?
As in many things wordpress, inertia has a lot to do with why things are done in specific way. Early core themes were written using those constructs and later developers copied them because they either did not know better or thought there was some non obvious reason to prefer them. As @Howdy_McGee said, it is just a style preference but I would avoid the `endif`, `endwhile` as curly braces are standard block delimiters across many languages and therefor are in general easier to read even if we will ignore the benefit of syntax highlighting and block collapsing in general editors.
stackexchange-wordpress
{ "answer_score": 8, "question_score": 2, "tags": "php" }
Remove &nbsp; from shortcode I'm not sure why I can't get this to work. I'm trying to remove the `&nbsp;` that is added inside this shortcode... [box] Text [/box] Which results in this HTML output: <div class="box">&nbsp; Text &nbsp;</div> I want to remove those spaces. I tried to usr str_replace, but it's not removing the &nbsp : function infoButton($atts, $content = null) { extract( shortcode_atts( array( 'class' => '', ), $atts )); $str = '<div class="box ' . $class . '">' . do_shortcode($content) . '</div>'; $new_str = str_replace('&nbsp;','',$str); return $new_str; } add_shortcode('box', 'infoButton');
This could be due to the `do_shortcode` running through `wpautop`, see here for details on disabling that: < But as `frogg3862` said, what you need to do instead of that is to just trim out the beginning and ending whitespace from `$content` to prevent the non-breaking space from being automatically added. function infoButton($atts, $content = null) { extract( shortcode_atts( array( 'class' => '', ), $atts )); $str = '<div class="box ' . $class . '">' . do_shortcode( trim( $content ) ) . '</div>'; return $str; } add_shortcode('box', 'infoButton');
stackexchange-wordpress
{ "answer_score": 0, "question_score": 1, "tags": "php, shortcode" }
Custom comment-field form arrangement How can I move my custom comment fields above the comment field? Currently i am using hooks `comment_form_after_fields` and `comment_form_logged_in_after`. Unfortunately due to Wordpress 4.4 changes, when a user is not logged-in the comment field is shown first and then the 'Name' and 'email' default fields. This means my custom fields are below the default fields. I have 'comment-title' and 'rating'fields that I need above the comment field. Is there another Hook I could use? If not should I resort to editing a comment comments.php?
Sure, you could use the `comment_form_field_comment` filter to inject content (extra fields or whatever) above the comment field: function comment_form_field_comment_add_field( $field ) { $new_field = '<p class="comment-form-extra"><label for="extra">Extra Field</label> <input id="extra" name="extra" type="text" value="" size="30" aria-required="true" required="required"></p>'; $field = $new_field . $field; return $field; } add_filter( 'comment_form_field_comment', 'comment_form_field_comment_add_field' ); You could also switch that around to put the new/extra field below the comment field: $field = $field . $new_field; Screenshot with twentyfourteen: <
stackexchange-wordpress
{ "answer_score": 1, "question_score": 0, "tags": "comment form" }
Browser is showing Javascript code instead of processing it Currently I've tried this process with two browsers: Google Chrome and Mozilla Firefox. Whenever I want to run a JavaScript code on them they show me the raw code instead of executing it. Exactly what I wrote in my Editor will be shown in the browser screen. Hope someone can help. ## Edit > Hey, am not using wordpress. Sorry that I didn't put the code here. Here is the code in my text Editor: <Script> Document.write("hello world") </script> This is what it output .... <Script> Document.write("hello world") </script> The same thing.
I see a couple of issues in the code you have posted. The script tag should be written properly: <script type="text/javascript"> //Code </script> It is `document.write`, with a small case `d`. If your code is in a separate JavaScript file, then you can include it and mention the source in the `script` tag. If you're directly writing it in the `head` tag, please try with the proper syntax as I have mentioned above.
stackexchange-wordpress
{ "answer_score": 0, "question_score": -4, "tags": "javascript" }
How to create wordpress plugin support page? I want to add a support page to my plugin wordpress. My plugin is already developed. Now I want to allow users to contact me for any question. I want the support button to be next to the activate and Update buttons in the plugin add page.
You can use the `plugin_action_links_`) filter for that task: add_filter( 'plugin_action_links_' . plugin_basename(__FILE__), 'add_support_link_wpse_220726' ); function add_support_link_wpse_220726( $links ) { $links[] = '<a href=" target="_blank">Support</a>'; return $links; } Note that you must also pass the plugin name (`plugin_basename(__FILE__)`) for it to work. That's why take into consideration from where you will call it.
stackexchange-wordpress
{ "answer_score": 2, "question_score": -2, "tags": "plugin development" }
"Add media" dialog is not showing any images When pressing the "add media"-button on the edit post page, it opens and the loader keeps spinning without it displaying any images. The images shows up just fine in the media library tab of the control panel. Things I've tried so far: * Changing theme to TwentySixteen (this works) * Disabling all plugins (currently have none installed) * Tried running the theme one a different install (does not work, same issue) * Empty out the functions.php file (no difference, also note that all javascripts are enqueued and registered from functions.php) * Replace all the WordPress files in the environment So I've kind of narrowed it down to it being a theme-issue. I just can't figure out which part of the theme that might affect the behavior of the "add media" function in WordPress. Anyone have suggestions to as which files in the theme might affect control panel behavior?
After switching workstation the issue became more obvious. When trying to log in, WordPress returned a blank login page. As I didn't get this symptom on the previous workstation as I was logged in, I didn't see the solution. The blank login page was related to malformed function.php with blank spaces at the beginning of file. Cleared excess spaces/ breaks from beginning of functions.php Solved following issues: Blank loginpage, blank "add media" dialog and no redirect on saving options.
stackexchange-wordpress
{ "answer_score": 0, "question_score": 0, "tags": "theme development" }
How to modify title tag in a plugin? I would like to add a meta value to the title `<title>` tag in a custom post typed page. So there would be meta value before normal post title. I have a custom field created that contains the needed data, but I don't know how to show it in the `<title>`. I can show it in pages `<h1>` in a template file, but I need the title tag to start with that data. How to do this? My theme uses `<?php wp_head(); ?>` and `add_theme_support( 'title-tag' );` to print title.
What I actually ended up doing was to use filter document_title_parts. < I just unshifted a value to the array. I don't think the documentation actually is very clear about that. And this method still don't work with Yoast SEO installed.
stackexchange-wordpress
{ "answer_score": 0, "question_score": 0, "tags": "title, wp title" }
oEmbed work on localhost but not on distant server I've a trouble with oEmbed integration for YouTube on hosting server. I've a Wordpress site that is exactly the same on my localhost (MAMP 3.0.7.3 on MacOSX with PHP Version 5.6.2) and my distant serveur (LAMP with Apache2 and PHP Version 5.6.17-0+deb8u1). On the localhost, when I paste an URL from Youtube the frame appear but not on the hosted version, where I've this response : `{"success":false,"data":{"type":"not-embeddable","message":"<code>https:\/\/www.youtube.com\/watch?v=luvQwgRZ9bo<\/code> n&rsquo;a pas pu \u00eatre int\u00e9gr\u00e9."}}` The commun troubleshooting (like change theme or disable plugin) have no effect. Maybe oEmbed need Apache2 mod or dependencies to work ? In this case I having ssh access to this server. Could you, please, help me?
It's a missing configuration on the apache hosts file which cause troubles on serveur 'self call'. For exemple, if serveur is using domain.com, I've a timeout when I typing `curl domain.com` with shh. Adding `127.0.0.1 domain.com` in /etc/hosts file and it's work !
stackexchange-wordpress
{ "answer_score": 1, "question_score": -1, "tags": "apache, oembed" }
how to get recent registered author id? I have tried to get the recently registered author user ID. i have no code now, because the below code can't use role to filter it. SELECT max(ID) FROM $wpdb->users LIMIT 1 and `get_users`function can get list of the users. not sure.how to obtain results.
I don't think you need any SQL queries. <?php $args = array( 'role' => 'author', // authors only 'orderby' => 'registered', // registered date 'order' => 'DESC', // last registered goes first 'number' => 1 // limit to the last one, not required ); $users = get_users( $args ); $last_user_registered = $users[0]; // the first user from the list echo $last_user_registered->ID; // print user ID Here you can find complete information on how to use `get_users()` function.
stackexchange-wordpress
{ "answer_score": 6, "question_score": 2, "tags": "users" }
Best way to save postmeta Just wondering what the best way to save postmeta is. I don't want empty postmeta values clogging up the database. I had already been saving postmeta in my plugin, which was adding empty values, so I'd like to clean those up as people re-save their posts. Any opinions on doing it like this? Improvements?: if ( isset( $_POST[ '_my_meta_key' ] ) && $_POST[ '_my_meta_key' ] !== '' ) { update_post_meta( $post_id, '_my_meta_key', $_POST[ '_my_meta_key' ] ); } else { delete_post_meta( $post_id, '_my_meta_key' ); }
Your approach is good, you should run a basic check against the data tough. Otherwise you might get an array or a serialized object … which might lead to unexpected consequences (including security issues!) when you or someone else is trying to print the values. Maybe something like this is easier: $key = '_my_meta_key'; $value = filter_input( INPUT_POST, $key, FILTER_SANITIZE_STRING ); if ( $value ) update_post_meta( $post_id, $key, $value ); else delete_post_meta( $post_id, $key ); Note that you should avoid writing the key string more than once. If you ever want to change its name, you should have as few places to search for it as possible. Ideally, just one in your whole code base.
stackexchange-wordpress
{ "answer_score": 4, "question_score": 1, "tags": "post meta" }
Custom Post Type for Shortcode Use - Prevent it display as a post (with slug) I've developed a series of plugins which can display categorised custom post types via shortcodes, along the lines of: [myshortcode myshortcodegroup="groupname"] This works just fine, however, I only want the custom content to be displayed via the use of a shortcode. In other words, the content should **NOT** be accessible via `slug/post-name`.
This is most likely a matter of configuring CPT registrations. `register_post_type()` has a lot of arguments related to visibility and access. On top of my head to prevent CPT from having front-end links and queries you would want to set `publicly_queryable` to `false`.
stackexchange-wordpress
{ "answer_score": 1, "question_score": 0, "tags": "custom post types, shortcode, slug" }
Is it possible to slow down site with a bulky child theme? I am creating a child theme for my theme and as I go through all the modifications that I want, I am almost overriding all the templates and adding a functions to the theme and had to dequeue some styles and scripts to be able to override it. While I know overriding the templates has no effect on the speed, because the parent templates dont get loaded when there is a child version, but I don't know how much (if any) resources the loading of unused functions in the parent take up or if dequeing many styles and scripts take up resources. So the question is if there comes a point sometime in child theme development when it is better to take over the theme development and just integrate the changes and use without a child theme? Or is it not worth thinking about there is probably little to no difference between using a child theme with a lot of overrides to using a modified parent theme?
Yes. There is a definitely a point where you just want to create a new theme. Unless you are writing more than a thousand lines of code, I would not be worried about performance problems with your child theme, if the parent theme is well-constructed. Adding conditional statements to test if scripts and styles are needed for certain pages will improve site response, not reduce it. The amount of processing time for the server to test three PHP `if` statements is negligible.
stackexchange-wordpress
{ "answer_score": 0, "question_score": 0, "tags": "child theme" }
WooCommerce: Adding Order Item Meta Data That's Hidden I was under the impression that if you add an underscore to your meta_key, it would be hidden from the Admin and subsequently the Order Receipts, etc. But, mine are showing? I don't understand what's going on... meta_key: `_testing_this`, meta_value: `asdasdasd` How do I added order item meta without it showing up?
The answer is to serialize the data you want to be hidden for sure.
stackexchange-wordpress
{ "answer_score": 0, "question_score": 1, "tags": "woocommerce offtopic, post meta, underscore" }
Check if Page Slug Exists, then display that Page's Title Came across this function to check if a page exists by its slug and it works great function the_slug_exists($post_name) { global $wpdb; if($wpdb->get_row("SELECT post_name FROM wp_posts WHERE post_name = '" . $post_name . "'", 'ARRAY_A')) { return true; } else { return false; } } but what i'm needing to do now is check if that exists, then output the title for that page, any help is appreciated. so when i put this code on the page to lookup the slug: <?php if (the_slug_exists('page-name')) { echo '$post_title'; } ?> everything is perfect other than the fact I need the function to output the title as well as lookup the slug, hopefully that makes more sense.
looking at MySQL query in the function it becomes clear that though it matches the post_name and returns true or false. What you want to find is, if a page exists by its slug. So, in that case, the function you have chosen is wrong. To get the page by title you can simply use: $page = get_page_by_title( 'Sample Page' ); echo $page->title Just in case if you want to get page by slug you can use following code: function get_page_title_for_slug($page_slug) { $page = get_page_by_path( $page_slug , OBJECT ); if ( isset($page) ) return $page->post_title; else return "Match not found"; } You may call above function like below: echo "<h1>" . get_page_title_for_slug("sample-page") . "</h1>"; Let me know if that helps.
stackexchange-wordpress
{ "answer_score": 4, "question_score": 0, "tags": "functions" }
Create a table in custom plugin on the activating it? I'm trying to create a custom plugin where I want create a table when the plugin gets activated. I have tried the following code but it is not creating the table in the database function create_plugin_database_table() { global $wpdb; $table_name = $wpdb->prefix . 'sandbox'; $sql = "CREATE TABLE $table_name ( id mediumint(9) unsigned NOT NULL AUTO_INCREMENT, title varchar(50) NOT NULL, structure longtext NOT NULL, author longtext NOT NULL, PRIMARY KEY (id) );"; require_once( ABSPATH . 'wp-admin/includes/upgrade.php' ); dbDelta( $sql ); } register_activation_hook( __FILE__, 'create_plugin_database_table' );
You have to include wpadmin/upgrade-functions.php file to create a table example function create_plugin_database_table() { global $table_prefix, $wpdb; $tblname = 'pin'; $wp_track_table = $table_prefix . "$tblname "; #Check to see if the table exists already, if not, then create it if($wpdb->get_var( "show tables like '$wp_track_table'" ) != $wp_track_table) { $sql = "CREATE TABLE `". $wp_track_table . "` ( "; $sql .= " `id` int(11) NOT NULL auto_increment, "; $sql .= " `pincode` int(128) NOT NULL, "; $sql .= " PRIMARY KEY `order_id` (`id`) "; $sql .= ") ENGINE=MyISAM DEFAULT CHARSET=latin1 AUTO_INCREMENT=1 ; "; require_once( ABSPATH . '/wp-admin/includes/upgrade.php' ); dbDelta($sql); } } register_activation_hook( __FILE__, 'create_plugin_database_table' );
stackexchange-wordpress
{ "answer_score": 18, "question_score": 8, "tags": "plugins, plugin development" }
How to get the active theme's slug? I'm able to get certain info about the active theme using `wp_get_theme()`. For example: $theme = wp_get_theme(); echo $theme->get( 'TextDomain' ); // twentyfifteen echo $theme->get( 'ThemeURI' ); // Is there a way to get the theme's slug? In this case it'd be _twentyfifteen_. Please note the theme's slug isn't always the same as the theme's text domain. I'd also like to avoid performing string replacement on the theme's URL if possible. Ref: <
I found the closest thing to the theme's slug is the theme's directory name. This can be found using `get_template()`: echo get_template(); // twentyfifteen Ref: <
stackexchange-wordpress
{ "answer_score": 1, "question_score": 6, "tags": "plugins, php, themes" }
Can I remove or edit an include() from a function with a filter? I need to edit the output of a plugin and the part I need to change is actually a html file that is brought in using include(name-of-file.html). The function has a filter, but I am just now beginning to understand how filters work, and cannot seem to figure out how to change that path. Basically, I want to change the path to point to /my-theme/name-of-file.html instead, and I want to use a filter so whenever I need to update the plugin I don't need to remember to, or have to, edit the file again. At any rate, this is the filter `add_filter('eventon_eventCard_evotx', array($this, 'frontend_box'), 10, 2);` and the function is `function frontend_box($object, $helpers){ .....stuff that stays.... include(name-of-file); .....more stuff that stays..... }` I would appreciate any help you guys could offer or point me towards
It is not (easily) possible to interfere with PHP `include`. What you can do in general is: 1. Fork a function (create your own copy under different name) 2. `remove_filter()` the original function 3. `add_filter()` of your function in its place However that can get impractical very fast. If the file being loaded makes sense to be customizable the first thing I would do is suggest to plugin developers to make it _easily_ so, introducing a specific filter for it or otherwise.
stackexchange-wordpress
{ "answer_score": 1, "question_score": 0, "tags": "php, plugin development, filters" }
About a programming language starts with <# #> Is that a Javascript code?? The following code inside a php class file but after closing php tag start these lines and the [data] variable not defined in this class i want to trace the [data] variable, where could i find it .. in js files?? and how the data passed through this variable inside php class (not even in global namespace) <# if ( data.tooltip ) { #> <a href="#" data-hint="{{ data.tooltip }}"></a> <# } #> Thanks, Best
If you are looking at core source then what you see it use is Underscore.js template. WordPress has slightly modified the syntax of templates themselves, but it's the library it uses. As far as I remember it was added when some parts of admin interface became more _rich_ and interactive, starting with media management. Unfortunately at the time (and still since) this part of WordPress is grossly underdocumented. As far as I am aware there is simply _none_ official documentation for it. You could check out the post Intro to Underscore.js templates in WordPress for some introduction to the concepts and mechanics.
stackexchange-wordpress
{ "answer_score": 1, "question_score": 0, "tags": "plugin development, ajax, javascript" }
How to set wp_options in functions.php for removeing the Default Front Page I want to disable the default front page as I want to show always the first listed page in the frontend. Therefor I disable the Static Front Page. But I have also to set in **wp_options** the variables **show_on_front** and **page_on_front** to remove the old default Front Page. I can manipulate the variables in the DB: UPDATE wp_options SET option_value = 'page' WHERE option_name = 'show_on_front'; UPDATE wp_options SET option_value = '0' WHERE option_name = 'page_on_front'; How can I set this variables fix in my `functions.php`? Or is that the wrong approach?
You can use following: update_option( 'show_on_front', 'page' ); update_option( 'page_on_front', '0' ); I hope this helps.
stackexchange-wordpress
{ "answer_score": 3, "question_score": 0, "tags": "theme development, frontpage, options" }
Display post from a date range from custom field I currently have a custom post type that has two major custom fields that are need for the query. The 'score_time' field stores time of a score. Example: 12:20 The 'score_date' stores the date the game took place. Example: 01/22/2016 I need query to display post from a specified date range and they are ordered by the 'score_time' field value Right now I don't have the date range working, but here is the code i have right now. $args = array( 'post_type' => 'score_post_type', 'posts_per_page' => 5, 'meta_key' => 'score_time', 'orderby' => 'meta_value', 'order' => 'ASC', );
The magic parameter ist described at WP_Query under: **Custom Field Parameters** You need to add a `meta_query` array to your `$args` where you define your range. In your case the code could look like this: $range = array( '2015-05-01', '2015-05-31', ); $args = array( 'post_type' => 'score_post_type', 'posts_per_page' => 5, 'meta_key' => 'score_time', 'orderby' => 'meta_value', 'order' => 'ASC', 'meta_query' => array( array( 'key' => 'score_date', 'value' => $range, 'compare' => 'BETWEEN', 'type' => 'date', ) ), ); **NOTE:** Make sure that your date and time values are valid SQL date/time values. Your provided format MM/DD/YYYY is bad for sorting and querying. Better: YYYY-MM-DD.
stackexchange-wordpress
{ "answer_score": 2, "question_score": 0, "tags": "custom post types, wp query, custom field" }
Modify Maximum upload file size text I have an issue with user uploading large images. I have prevented this with this snippet... add_filter('wp_handle_upload_prefilter', 'f711_image_size_prevent'); function f711_image_size_prevent($file) { $size = $file['size']; $size = $size / 1024; // Calculate down to KB $type = $file['type']; $is_image = strpos($type, 'image'); $limit = 5000; // Your Filesize in KB if ( ( $size > $limit ) && ($is_image !== false) ) { $file['error'] = 'Image files must be smaller than '.$limit.'KB'; } return $file; } This works great but the Media Upload page still shows text saying "Maximum upload file size: 64 MB" I assume it pulls this value from the servers PHP config, is there a way to modify this text?
This text is coming from `wp-admin/includes/media.php#L1946` There is not filter is available to modify the text. But still if you wish you can use `gettext` filter to modify the text. add_action('post-html-upload-ui', function () { add_filter('gettext', 'media_upload_limit_custom_text'); }); /** * Customize the max media size text * @param string $text * @return string $text */ function media_upload_limit_custom_text($text) { if ($text == 'Maximum upload file size: %s.') { return __('Image files must be smaller than 5000 KB', 'your-text-domain'); } return $text; } We are adding `gettext` filter just before our text is being display!
stackexchange-wordpress
{ "answer_score": 1, "question_score": 2, "tags": "php, uploads" }
How make wp_nav() with my css? I'm make small theme for company. We have html code made by fronted developer. How will be code menu from html to wordpress by php. <nav class="top-nav"> <a href="">О студии</a> <a href="pricing.html">Стоимость работ</a> <a href="">Галерея работ</a> <a href="">Важное о наращивании</a> </nav>
First step is to register the name (or names) for your menus. In your example, top-nav seems appropriate. function vd_register_menu() { register_nav_menu('top-nav',__( 'Top Nav Menu' )); } add_action( 'init', 'vd_register_menu' ); This will allow you to build your menu items in the WP admin under Appearance > Menus. To display your menu on the site, simply call the `wp_nav_menu()` function where you wish to print the code. <?php wp_nav_menu( array( 'theme_location' => 'top-nav' ) ); ?> Full documentation available via WP Codex: <
stackexchange-wordpress
{ "answer_score": 1, "question_score": -2, "tags": "php, html" }
Wordpress Links Not Working After Migration Just finished moving my local Wordpress install to a live server. Imported my DB, and uploaded my core files to the new server. I also changed the siteurl and home fields in the wp_options table and added the new credentials to the new wp_config file. Basically followed all the directions here. The issue is my links are not working. They're redirecting I assume to the parent Wordpress index install. Heres the file structure of my server -public_html (I have 4 add-on domains here) ----merchantsofdesign.ca (also a wordpress install) --------clients ------------creditassur ----------------wordpress (core files are here) Can I even have a parent folder and child folder both running Wordpress? Thanks and hope that makes sense
Go to settings » permalinks and save changes again.
stackexchange-wordpress
{ "answer_score": 6, "question_score": 2, "tags": "permalinks, errors, migration" }
Creating two Columns on a Page. The page I am trying to edit is as follows: < I am using the Wordpress Simple PayPal Shopping Cart Plugin and I want the two items I have on the page in two columns to make it look more organized. Any idea on how to do this?
You can do this with the CSS: .wp_cart_product_display_box {float:left;} You will probably want to add something like `margin-right: 30px;` to that. PS. You have a rogue `</p>` tag on the page also, check your content/template for syntax errors.
stackexchange-wordpress
{ "answer_score": 0, "question_score": -3, "tags": "columns" }
Want to show pop up image on home page every time when i refresh it i want to show pop up image on my home page when i open my site. And when i refresh the page it should appear again as a pop. I could not find such plugin. Is there any plugin for it ?
I think there are lots of plugin available for this kind of popup. You just have to make some changes and that's all. Can you please visit the following links that i have found and will definitely meet your requirements. Free Plugin Demo
stackexchange-wordpress
{ "answer_score": 0, "question_score": -2, "tags": "plugins, images" }
Why Should We Use wp_clear_scheduled_hook and What it Does? I am new to cron job. After reading this article I was able to run a function every hour using `wp_schedule_event`. There is a quote on "Don't forget to clean the scheduler on deactivation" in that page. I read the documentation of `wp_clear_scheduled_hook`. But still I could not understand why we should use `wp_clear_scheduled_hook` and what it do.
If you deactivate the plugin, the scheduled event will still try to run ( and fail ) unless you remove that event from the schedule using wp_clear_scheduled_hook
stackexchange-wordpress
{ "answer_score": 5, "question_score": 2, "tags": "actions, wp cron" }
Does something like is_rest() exist I am starting a bit with the REST API. If I am not completly mislead, the `init` action hook is also executed when its a REST API request. Now, I want to execute some code only, when it is not a REST API request. So I was looking for a command like `is_rest()` in order to do something like <?php if( ! is_rest() ) echo 'no-rest-request'; ?> But I couldn't find something like this. Is there a `is_rest()` out there?
It's a good point by @Milo, the `REST_REQUEST` constant is defined as `true`, within `rest_api_loaded()` if `$GLOBALS['wp']->query_vars['rest_route']` is non-empty. It's hooked into `parse_request` via: add_action( 'parse_request', 'rest_api_loaded' ); but `parse_request` fires later than `init` \- See for example the Codex here. There was a suggestion (by Daniel Bachhuber) in ticket #34373 regarding `WP_Query::is_rest()`, but it was postponed/cancelled.
stackexchange-wordpress
{ "answer_score": 21, "question_score": 28, "tags": "rest api" }
Download button for Featured Image in every post - automatically I want to add download button for featured image in every post automatically in WordPress with the usage of php files. I don't want to use shortcodes, custom html in every post or plugins, cause I need automated, simple and reliable solution. This is my code showing featured image in the single post content page. <div <?php post_class( 'inside item' ); ?>> <a href="<?php the_permalink(); ?>"><?php the_post_thumbnail( 'post-page', array( 'class' => 'featured-image' ) ); ?></a> Underneath I would like to add a button to download this particular image: <a class="download_image" href="<?php featured-image-link?; ?>" >Download this Image</a> But I don't know how to provide an automatic link to the photo in its full size (which can be seen above). Thanks for all your suggestions and comments!
You can use `the_post_thumbnail_url();` to get the thumbnail URL. More infos about the function: < <a class="download_image" href="<?php the_post_thumbnail_url( 'full' ); ?>">Download this Image</a>
stackexchange-wordpress
{ "answer_score": 0, "question_score": 0, "tags": "images, post thumbnails" }
What does this if-statement do?: if($pages=' ') {} This is an excerpt from a tutorial on how to create pagination for an blogpost overview page. What does the first part `if($pages == ''` _exactly_ do? > **_Quote from tutorial:_** Now we know which page we are currently viewing, but we also need to know how many pages we got. We are still asuming that we are not using a custom loop and that the $pages variable (dont mix up with $paged) was not set when we called the script. If thats the case we can once again make use of a global variable to get that number: if($pages == '') { global $wp_query; $pages = $wp_query->max_num_pages; if(!$pages) { $pages = 1; } }
`$pages` is an optional parameter. If not set, `$pages` will equal an empty string. So `if($pages == '')` checks to see if that parameter has been set. In this call, the parameter has not been set: `kriesi_pagination();` In this call, the parameter _has_ been set: `kriesi_pagination(5);` In the tutorial link that you posted, read this section again, the part that starts > As you can see we got 2 optional parameters to pass:
stackexchange-wordpress
{ "answer_score": 1, "question_score": -3, "tags": "php, pagination" }
get_term_by "name" not working with & in name I want to get category id by name so I am using get_term_by This is working fine when name is simple but when '&' is coming in term name it is not fetching category id. e.g I have a term named "Website Development & Designing" under **skills** taxonomy and I am using following query to get its term id. $value = "Website Development & Designing" get_term_by('name',$value,'skills'); but it does not return term object :(
The characters <, >, &, " and ' (less than, greater than, ampersand, double quote and single quote) are enconded in term names. & becomes `&amp;`. This is done by passing the term object to `sanitize_term()` function which applies several filters. By default WordPress applies theses filters: `sanitize_text_field()`, `wp_filter_kses()` and `_wp_specialchars()` (see `wp-includes/default-filters.php`), this last function encondes <, >, &, " and '. So, you need to do: `$value = "Website Development &amp; Designing" get_term_by('name',$value,'skills');` Or, for unknown values: `get_term_by( 'name', esc_attr( $value ), 'skills');` NOTE: use `esc_attr()`, not `_wp_specialchars()` directly because `_wp_specialchars()` is marked as private function and it is not intended for use by plugin or theme developers.
stackexchange-wordpress
{ "answer_score": 1, "question_score": 1, "tags": "terms" }
Display taxonomy term only if there's a value I have a post type which I want to add some taxonomy values (tags) Example Post Type One 1. **City** : London, Paris 2. **Color** : Red, Yellow 3. **Language** : In the example above, Language doesn't have any value, therefore, I want to hide it. I have this code: <?php $lang= get_terms( 'lang' ); if ( !empty( $lang)) { echo '<li><strong>Language:</strong>'; the_terms( $post->ID, 'lang', ' ', ', ' ); echo '</li>'; } ?> But **Language** will still appear even though I don't add any tags on it.
`get_terms()` return all the terms in the taxonomy regardless of the current post. So if current post does not have **lang** terms still this condition `if ( !empty( $lang))` will be `true` thus it will display the text **Language**. Use `get_the_term_list` instead of `the_terms` which return the terms list instead of printing, so output can be used for both purpose. Example:- $lang = get_the_term_list( get_the_ID(), 'lang', ' ', ', ' ); if ( !empty( $lang)) { echo '<li><strong>Language:</strong>' . $lang . '</li>'; } > Note: Recommended approach is to use `get_the_ID()` instead of global `$post->ID`
stackexchange-wordpress
{ "answer_score": 3, "question_score": 0, "tags": "custom post types, posts, custom taxonomy, taxonomy" }
All post of child category not in top category i have data category: - About us -- Sub 1 about us -- Sub 2 about us In Categor `About us` a has add post : `About us 1, About us 2, About us 3....` In Sub category `Sub 1 about us` i has add list post: `Sub 1 about us 1, Sub 1 about us 2...` In Sub category `Sub 2 about us` i has add list post: `Sub 2 about us 1, Sub 2 about us 2...` How to: In Archive Category `About us` echo list post of `Sub 1 about us & Sub 2 about us` not show `About us 1, About us 2, About us 3....` in category `About us` Any idea? Thanks!
Maybe something like this would do? $cat = 'About us'; $tax = 'category'; $cat_id = get_cat_ID($cat); $category = get_term_children($cat_id, $tax); $pre = ''; foreach ($category as $sub) { $cat_list .= $pre . $sub; $pre = ', '; } query_posts(array( 'cat' => $cat_list, 'posts_per_page' => 1000)); echo '<ul>'; while ( have_posts() ) : the_post(); echo '<li>'; the_title(); echo '</li>'; endwhile; echo '</ul>';
stackexchange-wordpress
{ "answer_score": 0, "question_score": -1, "tags": "categories, archives" }
Use customizer or sidebar for header settings? I'm converting html into Wordpress theme. In the header I have a tel number and a button. Both are links, but styled differently. Do you think it would be better to make them a sidebar (widget area) or as settings in customizer? What should be the principle choosing between customiser or widget area.
The customiser should not make a real difference in you decision as widgets are customized from the customizer as well. In general widget areas (sidebars) should be used whenever the user has the option to put any kind of content in it. If the content has to be very specific you should start looking into specific options.
stackexchange-wordpress
{ "answer_score": 0, "question_score": 0, "tags": "widgets, sidebar, theme customizer, options" }
How to change Woocommerce breadcrumbs content? I want to customize the breadcrumbs directly from PHP. Some of the pages are generated dynamically and do not exist in the database, therefore i must automatically put them in the breadcrumbs with some sort of PHP script. I don't need to change default stuff, like homepage url, separators, etc...but i actually need to manually put some pages in the breadcrumbs. I was trying with some filterings and some hooks. I've read the documentation but it just explains how to change default stuff. How can i change the actual content of the breadcrumbs? I tried this: add_filter( 'woocommerce_breadcrumb', 'change_breadcrumb' ); function change_breadcrumb( $defaults ) { // Change the breadcrumb home text from 'Home' to 'Appartment' //do something return $defaults; } But the `//do something` never executes. It's like if that filter never gets called
That is due to the fact, that your filter `woocommerce_breadcrumb` doesn't even exist. This filter here works and pulls out all the elements, that are currently in the breadcrumb (as an array): add_filter( 'woocommerce_get_breadcrumb', 'change_breadcrumb' ); function change_breadcrumb( $crumbs ) { var_dump( $crumbs ); return $crumbs; } And this filter pulls out the `main term` (as an object). add_filter( 'woocommerce_breadcrumb_main_term', 'change_breadcrumb' ); function change_breadcrumb( $main_term ) { var_dump( $main_term ); return $main_term; } The 'main term' is just the first element that is returned by this function (reference): $terms = wc_get_product_terms( $post->ID, 'product_cat', array( 'orderby' => 'parent', 'order' => 'DESC' ) ) See the Action and Filter Hook Reference by woothemes for all hooks & filters.
stackexchange-wordpress
{ "answer_score": 5, "question_score": 3, "tags": "filters, hooks, woocommerce offtopic" }
Create custom page in WooCommerce I would like to create a blank page, which is used to list out the product by the category , so far I have found some code like this: $args = array( 'post_type' => 'product', 'posts_per_page' => 100, 'product_cat' => 'hot-deals'); $loop = new WP_Query( $args ); while ( $loop->have_posts() ) : $loop->the_post(); global $product; var_dump($product); endwhile; wp_reset_query(); The problems is: 1) Where should I place the code? I tried adding it in the backend->add new page, I installed some plugin that allow me to insert PHP code, tested that the code is fine. However I would like to generate an XML from the result. If I simply create a page, it will include the header and footer in it. How to create a blank page and at the same time can use the Classes/ functions from woocommerce? e.g. my-domain.com/rss
1. Create a new page in /wp-admin (in the left column: Pages -> Add New); 2. create new custom page template after reading through this doc; 3. put your code in there; 4. go into the page you created in #1 and assign the page template to it (in the right column, Page Attributes box, the drop-down under 'Template' - your template should be on the list, if it's not then you did something wrong in #2 - or simply didn't refresh).
stackexchange-wordpress
{ "answer_score": 3, "question_score": 3, "tags": "posts, pages, woocommerce offtopic, xml" }
Where is the "ancestors" post object attribute? I usually work with the `ancestors` attribute of the post object: if ( in_array( $target_id, $post->ancestors ) ) { // do whatever } But while debugging the post object I've seen that there is no trace of it. Can someone help me understand the reason why this happens?
The reason you don't see it if you dump object is because it's not _actual_ object property. `WP_Post` implements magical `__get()` method for `ancestors` and several more keys like that. When you access `$post->ancestors()` what you actually get is not some value from the object, but return of `get_post_ancestors()` function executed on it. So in a nutshell this is like a virtual API shortcut.
stackexchange-wordpress
{ "answer_score": 4, "question_score": 2, "tags": "posts, debug, oop" }
Should I Worry About SQL Injection When Using wp_insert_post? I have created a form to insert posts via front-end to users. I use `wp_insert_post` function. Should I worry about SQL injection or Does `wp_insert_post` function handle it?
WordPress DOES take care of SQL injection and for you. See the **Security** section on this page. The `wp_insert_post()` function runs through `sanitize_post()`. Be aware that malicious or unintended code can still be inserted: > "You may wish, however, to remove HTML, JavaScript, and PHP tags from the `post_title` and any other fields. Surprisingly, WordPress does not do this automatically. This can be easily done by using the wp_strip_all_tags() function and is **especially useful when building front-end post submission forms**." Should you not want to strip ALL tags, Validating Sanitizing and Escaping User Data is a good page to start looking for specific sanitation rules that are built in. You can never be too secure.
stackexchange-wordpress
{ "answer_score": 3, "question_score": 1, "tags": "security" }
Custom shortcode not being included in content paragraph Ive created a custom shortcode via functions.php to display a phone number in the content when the shortcode is used in the WYSIWYG field. function contact() { $contact = get_field('contact',options); echo $contact; } add_shortcode('contact', 'contact'); However in the content editor when we write "contact us on [contact]" it comes out on the front end with the phone number first and then contact us on on the next line. I've also tried this: function contact() { $contact = get_field('contact',options); printf ('%s',$contact); } add_shortcode('contact', 'contact'); How can I please get this string to be included in the paragraph and not be on its own line above any content? Thanks, Adrian
The 'contact' function should return a string instead of echoing. So the above, should look like: function contact() { $contact = get_field('contact',options); return $contact; } add_shortcode('contact', 'contact'); > Shortcodes are written by providing a handler function. Shortcode handlers are broadly similar to WordPress filters: they accept parameters (attributes) and return a result (the shortcode output). See the codex for Shortcodes
stackexchange-wordpress
{ "answer_score": 1, "question_score": -1, "tags": "functions, shortcode" }
Auto move media file to cloud I have very little space to host my WordPress website. That is why I want all my media files are stored in the cloud like dropbox, google drive etc. For example, if a user wants to upload an image from the front-end using the common upload file button, then the image file is automatically stored directly to the cloud. or the image file will first stored in the upload folder then automatically moved into the cloud. So then my upload folder will always empty in order to save my very little space. How can I do this?
WP Offload S3 is pretty much the best WP -> Amazon s3 plugin out there
stackexchange-wordpress
{ "answer_score": 0, "question_score": 1, "tags": "plugins, uploads, media, cloud" }
Anyone can register via backend My question is simple. Is it possible to enable option " **Anyone can register** " with php function? Thanks.
Yes you can use following in PHP: update_option( 'users_can_register', $value ); Where $value can be **1** for `Yes` and **0** for `No`
stackexchange-wordpress
{ "answer_score": 5, "question_score": 1, "tags": "php" }
Wordpress text widget with onclick function I have a text widget, in it i just place there an iframe. A few days ago i wanted to override this widget on mobile browsers and add a background of an image on mobile browsers, luckily i used How to hide widget on mobile , i changed the code from that link instead of hiding the widget on mobile i simply give it a background image. Now my questions is how can i add an onclick function to this widget, for example when this widget is clicked on a mobile browser i call a shortcode. Any code examples of how to add some javascript to a text widget so that when it is clicked i call a shortcode.
Finally all i had to do is specify the mobile custom css code, i give it a name then make it only visible to mobile (800width and above are not mobile, probably tablet, pc e.t.c) @media only screen and (max-width : 800px) { .media{ display: none; } } @media only screen and (min-width : 800px) { .vid{ display: none; } } Then from my widget i add the image background pointing to a custom function i put in the header.php <img class="vid" onclick="myFunction();" src=" />
stackexchange-wordpress
{ "answer_score": 0, "question_score": 0, "tags": "javascript" }