qid
int64 4
8.14M
| question
stringlengths 20
48.3k
| answers
list | date
stringlengths 10
10
| metadata
list | input
stringlengths 12
45k
| output
stringlengths 2
31.8k
|
---|---|---|---|---|---|---|
288,301 | <p>I tried many many times, I read many examples but my .htaccess is not working.
My domain is: liebeundsprueche.com/
When I go to www.liebeundsprueche.com/ it doesn't redirect me to liebeundsprueche.com/
Here is my .htaccess file:</p>
<pre><code># BEGIN WordPress
<IfModule mod_rewrite.c>
DirectoryIndex index.php
RewriteEngine on
RewriteBase /
RewriteCond %{REQUEST_FILENAME} -f
RewriteRule ^ %{REQUEST_FILENAME} [L]
# invalid code - and useless if the ^ and % were joined
RewriteCond %{REQUEST_FILENAME} -d
RewriteCond %{REQUEST_FILENAME}/index.php -f
RewriteRule ^ %{REQUEST_FILENAME}/index.php [L]
# invalid code as the second condition can NEVER happen and the Rule is flawed (regex of ^ !!!).
RewriteCond %{HTTP_HOST} ^www\.liebeundsprueche\.com$
RewriteRule ^/?$ "http\:\/\/liebeundspruechee\.com\/" [R=301,L]
RewriteCond %{REQUEST_FILENAME} -d
RewriteCond %{REQUEST_FILENAME}/index.php !-f
RewriteRule ^ 404/ [L]
# ditto
RewriteRule ^(.*[^/]) index.php?var=$1 [QSA,L]
</IfModule>
# END WordPress
</code></pre>
<p>Please let me know where is the error?</p>
| [
{
"answer_id": 288402,
"author": "scytale",
"author_id": 128374,
"author_profile": "https://wordpress.stackexchange.com/users/128374",
"pm_score": 1,
"selected": false,
"text": "<p>Stage and Prod may be on the same server but are they configured for the same version of PHP?</p>\n\n<p>A Wordpress debug plugin <em>might</em> provide you with additional info. Query Monitor <a href=\"https://en-gb.wordpress.org/plugins/query-monitor/#description\" rel=\"nofollow noreferrer\">https://en-gb.wordpress.org/plugins/query-monitor/#description</a> provides a call stack for PHP Notices and Errors. After activation: as Admin User, go to an offending page. Not obvious, but the ribbon at the top should display seconds and KB, hover over this and click errors (I think). On my site (only a notice - no errors):</p>\n\n<p><a href=\"https://i.stack.imgur.com/GmSQQ.jpg\" rel=\"nofollow noreferrer\"><img src=\"https://i.stack.imgur.com/GmSQQ.jpg\" alt=\"Query Monitor ribbon\"></a></p>\n\n<p>Once you click Errors, details will be displayed including a call stack which <em>might</em> help.</p>\n\n<p>If PHP 7 is an issue - there is a compatibility checker somewhere in the WP Plugin directory which might be useful. It does give false positives e.g. a plugin may be marked incompatible even if it only uses a depracated function after checking PHP 7 is not being used by server.</p>\n"
},
{
"answer_id": 288408,
"author": "kierzniak",
"author_id": 132363,
"author_profile": "https://wordpress.stackexchange.com/users/132363",
"pm_score": 3,
"selected": true,
"text": "<p>You can create your own custom error handler and add stack trace to your error log.</p>\n\n<pre><code>set_error_handler('wpse_288408_handle_error');\n\nfunction wpse_288408_handle_error( $errno, $errstr, $errfile, $errline ) {\n\n if( $errno === E_USER_NOTICE ) {\n\n $message = 'You have an error notice: \"%s\" in file \"%s\" at line: \"%s\".' ;\n $message = sprintf($message, $errstr, $errfile, $errline);\n\n error_log($message);\n error_log(wpse_288408_generate_stack_trace());\n }\n}\n// Function from php.net http://php.net/manual/en/function.debug-backtrace.php#112238\nfunction wpse_288408_generate_stack_trace() {\n\n $e = new \\Exception();\n\n $trace = explode( \"\\n\" , $e->getTraceAsString() );\n\n // reverse array to make steps line up chronologically\n\n $trace = array_reverse($trace);\n\n array_shift($trace); // remove {main}\n array_pop($trace); // remove call to this method\n\n $length = count($trace);\n $result = array();\n\n for ($i = 0; $i < $length; $i++) {\n $result[] = ($i + 1) . ')' . substr($trace[$i], strpos($trace[$i], ' ')); // replace '#someNum' with '$i)', set the right ordering\n }\n\n $result = implode(\"\\n\", $result);\n $result = \"\\n\" . $result . \"\\n\";\n\n return $result;\n}\n</code></pre>\n\n<p>You can check if this is working by adding <code>trigger_error</code> somewhere in your code.</p>\n\n<pre><code>trigger_error('Annoying notice');\n</code></pre>\n\n<p>Your error log should output something like that:</p>\n\n<pre><code>2017/01/02 12:00:00 [error] 999#999: *999 FastCGI sent in stderr: \"PHP message: You have an error notice: \"Annoying notice\" in file \"/var/www/test/wp-content/plugins/test/test.php\" at line: \"99\".\nPHP message:\n1) /var/www/test/index.php(17): require('/var/www/test/w...')\n2) /var/www/test/wp-blog-header.php(13): require_once('/var/www/test/w...')\n3) /var/www/test/wp-load.php(37): require_once('/var/www/test/w...')\n4) /var/www/test/wp-config.php(93): require_once('/var/www/test/w...')\n5) /var/www/test/wp-settings.php(305): include_once('/var/www/test/w...')\n6) /var/www/test/wp-content/plugins/test/test.php(99): trigger_error('Annoying notice')\n7) [internal function]: wpse_288408_handle_error(1024, 'Annoying notice', '/var/www/test/w...', 99, Array)\" while reading response header from upstream, client: 192.168.33.1, server: test.dev, request: \"GET / HTTP/1.1\", upstream: \"fastcgi://127.0.0.1:9070\", host: \"test.dev\"\n</code></pre>\n\n<p>With this kind of message it will be much easier to find out where the problem is.</p>\n"
}
]
| 2017/12/11 | [
"https://wordpress.stackexchange.com/questions/288301",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/133070/"
]
| I tried many many times, I read many examples but my .htaccess is not working.
My domain is: liebeundsprueche.com/
When I go to www.liebeundsprueche.com/ it doesn't redirect me to liebeundsprueche.com/
Here is my .htaccess file:
```
# BEGIN WordPress
<IfModule mod_rewrite.c>
DirectoryIndex index.php
RewriteEngine on
RewriteBase /
RewriteCond %{REQUEST_FILENAME} -f
RewriteRule ^ %{REQUEST_FILENAME} [L]
# invalid code - and useless if the ^ and % were joined
RewriteCond %{REQUEST_FILENAME} -d
RewriteCond %{REQUEST_FILENAME}/index.php -f
RewriteRule ^ %{REQUEST_FILENAME}/index.php [L]
# invalid code as the second condition can NEVER happen and the Rule is flawed (regex of ^ !!!).
RewriteCond %{HTTP_HOST} ^www\.liebeundsprueche\.com$
RewriteRule ^/?$ "http\:\/\/liebeundspruechee\.com\/" [R=301,L]
RewriteCond %{REQUEST_FILENAME} -d
RewriteCond %{REQUEST_FILENAME}/index.php !-f
RewriteRule ^ 404/ [L]
# ditto
RewriteRule ^(.*[^/]) index.php?var=$1 [QSA,L]
</IfModule>
# END WordPress
```
Please let me know where is the error? | You can create your own custom error handler and add stack trace to your error log.
```
set_error_handler('wpse_288408_handle_error');
function wpse_288408_handle_error( $errno, $errstr, $errfile, $errline ) {
if( $errno === E_USER_NOTICE ) {
$message = 'You have an error notice: "%s" in file "%s" at line: "%s".' ;
$message = sprintf($message, $errstr, $errfile, $errline);
error_log($message);
error_log(wpse_288408_generate_stack_trace());
}
}
// Function from php.net http://php.net/manual/en/function.debug-backtrace.php#112238
function wpse_288408_generate_stack_trace() {
$e = new \Exception();
$trace = explode( "\n" , $e->getTraceAsString() );
// reverse array to make steps line up chronologically
$trace = array_reverse($trace);
array_shift($trace); // remove {main}
array_pop($trace); // remove call to this method
$length = count($trace);
$result = array();
for ($i = 0; $i < $length; $i++) {
$result[] = ($i + 1) . ')' . substr($trace[$i], strpos($trace[$i], ' ')); // replace '#someNum' with '$i)', set the right ordering
}
$result = implode("\n", $result);
$result = "\n" . $result . "\n";
return $result;
}
```
You can check if this is working by adding `trigger_error` somewhere in your code.
```
trigger_error('Annoying notice');
```
Your error log should output something like that:
```
2017/01/02 12:00:00 [error] 999#999: *999 FastCGI sent in stderr: "PHP message: You have an error notice: "Annoying notice" in file "/var/www/test/wp-content/plugins/test/test.php" at line: "99".
PHP message:
1) /var/www/test/index.php(17): require('/var/www/test/w...')
2) /var/www/test/wp-blog-header.php(13): require_once('/var/www/test/w...')
3) /var/www/test/wp-load.php(37): require_once('/var/www/test/w...')
4) /var/www/test/wp-config.php(93): require_once('/var/www/test/w...')
5) /var/www/test/wp-settings.php(305): include_once('/var/www/test/w...')
6) /var/www/test/wp-content/plugins/test/test.php(99): trigger_error('Annoying notice')
7) [internal function]: wpse_288408_handle_error(1024, 'Annoying notice', '/var/www/test/w...', 99, Array)" while reading response header from upstream, client: 192.168.33.1, server: test.dev, request: "GET / HTTP/1.1", upstream: "fastcgi://127.0.0.1:9070", host: "test.dev"
```
With this kind of message it will be much easier to find out where the problem is. |
288,307 | <p>In my plugin I'm using </p>
<p><code>add_filter('wp_insert_post_data','filter_blog_post_data');</code> </p>
<p>for filtering blog data before it gets saved in the database.</p>
<p>However this hook makes <code>post-new.php</code> to load latest post's data, like permalink, slug, author.</p>
<p><a href="https://i.stack.imgur.com/o1uSq.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/o1uSq.png" alt="enter image description here"></a></p>
<p><a href="https://i.stack.imgur.com/NInrt.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/NInrt.png" alt="enter image description here"></a></p>
<p>How to get rid of this bug? </p>
<p><strong>Note:</strong></p>
<p>I'm using <code>Wordpress 4.4.13</code>. </p>
| [
{
"answer_id": 288311,
"author": "Sid",
"author_id": 110516,
"author_profile": "https://wordpress.stackexchange.com/users/110516",
"pm_score": 1,
"selected": false,
"text": "<p>Not sure what must be causing this. Try replicating your entire filter hook with function in this format:</p>\n\n<pre><code>function filter_handler( $data ) {\n // do something with the post data\n return $data;\n}\n\nadd_filter( 'wp_insert_post_data', 'filter_handler', '10', 1);\n</code></pre>\n\n<p>Let me know if something happens.</p>\n"
},
{
"answer_id": 288685,
"author": "kierzniak",
"author_id": 132363,
"author_profile": "https://wordpress.stackexchange.com/users/132363",
"pm_score": 0,
"selected": false,
"text": "<p>The key is what's inside <code>filter_blog_post_data</code>. Returned array from this filter is also applying to your new, not saved yet post as well.</p>\n\n<pre><code>function wpse_288685_filter_data( $data, $postarray ){\n\n $data['post_name'] = 'foo-bar';\n\n return $data;\n}\n\nadd_filter('wp_insert_post_data', 'wpse_288685_filter_data', 10, 2);\n</code></pre>\n\n<p>This function will set post slug to <code>foo-bar</code> even when your are on <code>post-new.php</code> page.</p>\n"
}
]
| 2017/12/11 | [
"https://wordpress.stackexchange.com/questions/288307",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/133017/"
]
| In my plugin I'm using
`add_filter('wp_insert_post_data','filter_blog_post_data');`
for filtering blog data before it gets saved in the database.
However this hook makes `post-new.php` to load latest post's data, like permalink, slug, author.
[](https://i.stack.imgur.com/o1uSq.png)
[](https://i.stack.imgur.com/NInrt.png)
How to get rid of this bug?
**Note:**
I'm using `Wordpress 4.4.13`. | Not sure what must be causing this. Try replicating your entire filter hook with function in this format:
```
function filter_handler( $data ) {
// do something with the post data
return $data;
}
add_filter( 'wp_insert_post_data', 'filter_handler', '10', 1);
```
Let me know if something happens. |
288,345 | <p>I have a client who wants to display home plans (a custom post type) on their website in 2 differently branded sections, depending on which listing page the post is accessed from. I found this solution from @gmazzap from a few years ago, and it looks promising, but I can't make it work: <a href="https://wordpress.stackexchange.com/questions/130284/multiple-templates-for-custom-post-type">Multiple templates for custom post type</a></p>
<p>Specifically, it fails to modify the URL on the alternate listing page: it simply uses the slug specified in the CPT registration: </p>
<pre><code>'rewrite' => array( 'slug' => 'plan', 'with_front' => false ),
</code></pre>
<p>Which means when I click a plan link on 'page_kioskoverview,php' template it displays the post on the standard 'single-plans.php' template rather than the alternate 'single-kioskplans.php' template.</p>
<p>Here's what my code looks like:</p>
<pre><code>add_action('template_redirect', 'change_plans_plink');
function change_plans_plink() {
if (is_page_template('page_kioskoverview.php')) {
add_filter( 'post_link', 'plans_query_string', 10, 2 );
}
}
function plans_query_string( $url, $post ) {
if ( $post->post_type === 'plans' ) {
$url = add_query_arg( array('style'=>'alt'), $url );
}
return $url;
}
//designate alternative single template for above alt link
add_action('template_include', 'kiosk_plan_single');
function kiosk_plan_single($template) {
if( is_singular('plans') ) {
$alt = filter_input(INPUT_GET, 'style', FILTER_SANITIZE_STRING);
if ( $alt === 'alt' ) $template = 'single-kioskplans.php';
}
return $template;
}
</code></pre>
<p>After a few days looking at it (and trying some variations without success), I cannot spot the problem, but I must be missing something.</p>
| [
{
"answer_id": 288389,
"author": "kierzniak",
"author_id": 132363,
"author_profile": "https://wordpress.stackexchange.com/users/132363",
"pm_score": 3,
"selected": true,
"text": "<p>To display different templates for the same post type I would make 2 different links, check on which link I'm currently on and decide which template to load.</p>\n\n<p>Working example:</p>\n\n<pre><code>/**\n * Register event post type\n *\n * Registering event post type will add such a permalink structure event/([^/]+)/?$\n */\nfunction wpse_288345_register_event_post_type() {\n\n $labels = array(\n 'name' => __( 'Events' ),\n 'singular_name' => __( 'Event' ),\n 'add_new' => __( 'Add new' ),\n 'add_new_item' => __( 'Add new' ),\n 'edit_item' => __( 'Edit' ),\n 'new_item' => __( 'New' ),\n 'view_item' => __( 'View' ),\n 'search_items' => __( 'Search' ),\n 'not_found' => __( 'Not found' ),\n 'not_found_in_trash' => __( 'Not found Events in trash' ),\n 'parent_item_colon' => __( 'Parent' ),\n 'menu_name' => __( 'Events' ),\n\n );\n\n $args = array(\n 'labels' => $labels,\n 'hierarchical' => false,\n 'supports' => array( 'title', 'page-attributes' ),\n 'taxonomies' => array(),\n 'public' => true,\n 'show_ui' => true,\n 'show_in_menu' => true,\n 'show_in_nav_menus' => false,\n 'publicly_queryable' => true,\n 'exclude_from_search' => false,\n 'has_archive' => true,\n 'query_var' => true,\n 'can_export' => true,\n 'rewrite' => array('slug' => 'event'),\n 'capability_type' => 'post',\n );\n\n register_post_type( 'event', $args );\n}\n\nadd_action( 'init', 'wpse_288345_register_event_post_type' );\n\n/**\n * Add custom rewrite rule for event post type.\n *\n * Remember to flush rewrite rules to apply changes.\n */\nfunction wpse_288345_add_event_rewrite_rules() {\n\n /**\n * Custom rewrite rules for one post type.\n * \n * We wil know on which url we are by $_GET parameters 'performers' and 'summary'. Which we will add to\n * public query vars to obtain them in convinient way.\n */\n add_rewrite_rule('event/performers/([^/]+)/?$', 'index.php?post_type=event&name=$matches[1]&performers=1', 'top');\n add_rewrite_rule('event/summary/([^/]+)/?$', 'index.php?post_type=event&name=$matches[1]&summary=1', 'top');\n}\n\nadd_action('init', 'wpse_288345_add_event_rewrite_rules');\n\n/**\n * Add 'performers' and 'summary' custom event query vars.\n */\nfunction wpse_288345_register_event_query_vars( $vars ) {\n\n $vars[] = 'performers';\n $vars[] = 'summary';\n\n return $vars;\n}\n\nadd_filter( 'query_vars', 'wpse_288345_register_event_query_vars' );\n\n/**\n * Decide which template to load\n */\nfunction wpse_288345_load_performers_or_summary_template( $template ) {\n\n // Get public query vars\n $performers = (int) get_query_var( 'performers', 0 );\n $summary = (int) get_query_var( 'summary', 0 );\n\n // If performer = 1 then we are on event/performers link\n if( $performers === 1 ) {\n $template = locate_template( array( 'single-event-performers.php' ) );\n }\n\n // If summary = 1 then we are on event/summary link\n if( $summary === 1 ) {\n $template = locate_template( array( 'single-event-summary.php' ) );\n }\n\n if($template == '') {\n throw new \\Exception('No template found');\n }\n\n return $template;\n}\n\nadd_filter( 'template_include', 'wpse_288345_load_performers_or_summary_template' );\n</code></pre>\n"
},
{
"answer_id": 288422,
"author": "Ray Gulick",
"author_id": 30,
"author_profile": "https://wordpress.stackexchange.com/users/30",
"pm_score": 0,
"selected": false,
"text": "<p>Here's the alternative approach that I made work, using a GET parameter and conditional statements.</p>\n\n<ol>\n<li><p>On the alternate listing page, I added '?template=kiosk' to the permalinks.</p></li>\n<li><p>On the singles template (single-plans.php) I added the following to the top of the template (and of course 'endif' at bottom of template):</p>\n\n<pre>$kiosk = $_GET['template'];\nif(isset($kiosk)) :</pre></li>\n<li><p>Then, throughout the template, I created conditional statements based on whether or not there was a parameter, to display content appropriately:</p>\n\n<p><pre>if(isset($kiosk)) { \n show kiosk version\n } else {\n show standard version\n }</pre></p></li>\n</ol>\n"
},
{
"answer_id": 377425,
"author": "mattmaldre",
"author_id": 163379,
"author_profile": "https://wordpress.stackexchange.com/users/163379",
"pm_score": 0,
"selected": false,
"text": "<p>I was trying almost the exactly the same code too, and it wasn't working. There's just one change to make for this to operate completely. Just add <code>locate_template</code> to one line.</p>\n<p>Change</p>\n<pre><code>if ( $alt === 'alt' ) $template = 'single-kioskplans.php';\n</code></pre>\n<p>to</p>\n<pre><code>if ( $alt === 'alt' ) $template = locate_template('single-kioskplans.php');\n</code></pre>\n<p>The full code will look like this:</p>\n<pre><code>add_action('template_redirect', 'change_plans_plink');\nfunction change_plans_plink() {\n if (is_page_template('page_kioskoverview.php')) { \n add_filter( 'post_link', 'plans_query_string', 10, 2 );\n }\n}\nfunction plans_query_string( $url, $post ) {\n if ( $post->post_type === 'plans' ) { \n $url = add_query_arg( array('style'=>'alt'), $url );\n }\n return $url;\n}\n\n//designate alternative single template for above alt link\nadd_action('template_include', 'kiosk_plan_single');\nfunction kiosk_plan_single($template) {\n if( is_singular('plans') ) {\n $alt = filter_input(INPUT_GET, 'style', FILTER_SANITIZE_STRING);\n if ( $alt === 'alt' ) $template = locate_template('single-kioskplans.php');\n }\n return $template;\n}\n</code></pre>\n"
}
]
| 2017/12/11 | [
"https://wordpress.stackexchange.com/questions/288345",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/30/"
]
| I have a client who wants to display home plans (a custom post type) on their website in 2 differently branded sections, depending on which listing page the post is accessed from. I found this solution from @gmazzap from a few years ago, and it looks promising, but I can't make it work: [Multiple templates for custom post type](https://wordpress.stackexchange.com/questions/130284/multiple-templates-for-custom-post-type)
Specifically, it fails to modify the URL on the alternate listing page: it simply uses the slug specified in the CPT registration:
```
'rewrite' => array( 'slug' => 'plan', 'with_front' => false ),
```
Which means when I click a plan link on 'page\_kioskoverview,php' template it displays the post on the standard 'single-plans.php' template rather than the alternate 'single-kioskplans.php' template.
Here's what my code looks like:
```
add_action('template_redirect', 'change_plans_plink');
function change_plans_plink() {
if (is_page_template('page_kioskoverview.php')) {
add_filter( 'post_link', 'plans_query_string', 10, 2 );
}
}
function plans_query_string( $url, $post ) {
if ( $post->post_type === 'plans' ) {
$url = add_query_arg( array('style'=>'alt'), $url );
}
return $url;
}
//designate alternative single template for above alt link
add_action('template_include', 'kiosk_plan_single');
function kiosk_plan_single($template) {
if( is_singular('plans') ) {
$alt = filter_input(INPUT_GET, 'style', FILTER_SANITIZE_STRING);
if ( $alt === 'alt' ) $template = 'single-kioskplans.php';
}
return $template;
}
```
After a few days looking at it (and trying some variations without success), I cannot spot the problem, but I must be missing something. | To display different templates for the same post type I would make 2 different links, check on which link I'm currently on and decide which template to load.
Working example:
```
/**
* Register event post type
*
* Registering event post type will add such a permalink structure event/([^/]+)/?$
*/
function wpse_288345_register_event_post_type() {
$labels = array(
'name' => __( 'Events' ),
'singular_name' => __( 'Event' ),
'add_new' => __( 'Add new' ),
'add_new_item' => __( 'Add new' ),
'edit_item' => __( 'Edit' ),
'new_item' => __( 'New' ),
'view_item' => __( 'View' ),
'search_items' => __( 'Search' ),
'not_found' => __( 'Not found' ),
'not_found_in_trash' => __( 'Not found Events in trash' ),
'parent_item_colon' => __( 'Parent' ),
'menu_name' => __( 'Events' ),
);
$args = array(
'labels' => $labels,
'hierarchical' => false,
'supports' => array( 'title', 'page-attributes' ),
'taxonomies' => array(),
'public' => true,
'show_ui' => true,
'show_in_menu' => true,
'show_in_nav_menus' => false,
'publicly_queryable' => true,
'exclude_from_search' => false,
'has_archive' => true,
'query_var' => true,
'can_export' => true,
'rewrite' => array('slug' => 'event'),
'capability_type' => 'post',
);
register_post_type( 'event', $args );
}
add_action( 'init', 'wpse_288345_register_event_post_type' );
/**
* Add custom rewrite rule for event post type.
*
* Remember to flush rewrite rules to apply changes.
*/
function wpse_288345_add_event_rewrite_rules() {
/**
* Custom rewrite rules for one post type.
*
* We wil know on which url we are by $_GET parameters 'performers' and 'summary'. Which we will add to
* public query vars to obtain them in convinient way.
*/
add_rewrite_rule('event/performers/([^/]+)/?$', 'index.php?post_type=event&name=$matches[1]&performers=1', 'top');
add_rewrite_rule('event/summary/([^/]+)/?$', 'index.php?post_type=event&name=$matches[1]&summary=1', 'top');
}
add_action('init', 'wpse_288345_add_event_rewrite_rules');
/**
* Add 'performers' and 'summary' custom event query vars.
*/
function wpse_288345_register_event_query_vars( $vars ) {
$vars[] = 'performers';
$vars[] = 'summary';
return $vars;
}
add_filter( 'query_vars', 'wpse_288345_register_event_query_vars' );
/**
* Decide which template to load
*/
function wpse_288345_load_performers_or_summary_template( $template ) {
// Get public query vars
$performers = (int) get_query_var( 'performers', 0 );
$summary = (int) get_query_var( 'summary', 0 );
// If performer = 1 then we are on event/performers link
if( $performers === 1 ) {
$template = locate_template( array( 'single-event-performers.php' ) );
}
// If summary = 1 then we are on event/summary link
if( $summary === 1 ) {
$template = locate_template( array( 'single-event-summary.php' ) );
}
if($template == '') {
throw new \Exception('No template found');
}
return $template;
}
add_filter( 'template_include', 'wpse_288345_load_performers_or_summary_template' );
``` |
288,363 | <p>I am receiving this notice when trying to use the $wpdb->prepare function:</p>
<blockquote>
<p>Notice: wpdb::prepare was called <strong>incorrectly</strong>. The
query does not contain the correct number of placeholders (7) for the
number of arguments passed (4). Please see Debugging in
WordPress for more information. (This message was added in version
4.8.3.) in C:\wamp\www\wpml\wp-includes\functions.php on line 4139</p>
</blockquote>
<p>I looked at other posts on this topic and I don't see any of the same problems from those threads in my code. When developing this notice greatly slows down my application so I want to find a solution.</p>
<pre><code>function get_meta_range($meta_key) {
global $wpdb;
// $meta_key = '_price'
$include = '7275,7266,7256,7237,7196,7192,7164';
$min = floor( $wpdb->get_var(
$wpdb->prepare('
SELECT min(meta_value + 0)
FROM %1$s
LEFT JOIN %2$s ON %1$s.ID = %2$s.post_id
WHERE ( meta_key =\'%3$s\' OR meta_key =\'%4$s\' )
AND meta_value != ""
AND (
%1$s.ID IN (' . $include . ')
)'
, $wpdb->posts, $wpdb->postmeta, $meta_key, '_min_variation' . $meta_key )
) );
// $min = 15
}
</code></pre>
| [
{
"answer_id": 288365,
"author": "Tom J Nowell",
"author_id": 736,
"author_profile": "https://wordpress.stackexchange.com/users/736",
"pm_score": 1,
"selected": false,
"text": "<p>The <code>wpdb::prepare</code> says that you should not quote placeholders, yet in your code there is:</p>\n\n<pre><code>WHERE ( meta_key =\\'%3$s\\' OR meta_key =\\'%4$s\\' )\n</code></pre>\n\n<p>Also keep in mind that the meta table is designed to be fast when you already know the post ID, and WP already fetches all of the meta when you grab a post.</p>\n\n<p>So it would actually be much faster to use <code>get_post_meta</code> and calculate it in PHP, as the data has already been requested. Doing this query is both unnecessary, and potentially expensive</p>\n"
},
{
"answer_id": 288367,
"author": "Milo",
"author_id": 4771,
"author_profile": "https://wordpress.stackexchange.com/users/4771",
"pm_score": 2,
"selected": false,
"text": "<p>Numbered placeholders don't work as you'd expect, and are going to be removed altogether at some point in the future, so should be considered invalid syntax.</p>\n\n<p>So with this in mind, the error describes the problem- your query has 7 placeholders, but you only pass 4 values. For the repeated values, you just need to repeat them where you pass the substitutions.</p>\n"
}
]
| 2017/12/12 | [
"https://wordpress.stackexchange.com/questions/288363",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/58254/"
]
| I am receiving this notice when trying to use the $wpdb->prepare function:
>
> Notice: wpdb::prepare was called **incorrectly**. The
> query does not contain the correct number of placeholders (7) for the
> number of arguments passed (4). Please see Debugging in
> WordPress for more information. (This message was added in version
> 4.8.3.) in C:\wamp\www\wpml\wp-includes\functions.php on line 4139
>
>
>
I looked at other posts on this topic and I don't see any of the same problems from those threads in my code. When developing this notice greatly slows down my application so I want to find a solution.
```
function get_meta_range($meta_key) {
global $wpdb;
// $meta_key = '_price'
$include = '7275,7266,7256,7237,7196,7192,7164';
$min = floor( $wpdb->get_var(
$wpdb->prepare('
SELECT min(meta_value + 0)
FROM %1$s
LEFT JOIN %2$s ON %1$s.ID = %2$s.post_id
WHERE ( meta_key =\'%3$s\' OR meta_key =\'%4$s\' )
AND meta_value != ""
AND (
%1$s.ID IN (' . $include . ')
)'
, $wpdb->posts, $wpdb->postmeta, $meta_key, '_min_variation' . $meta_key )
) );
// $min = 15
}
``` | Numbered placeholders don't work as you'd expect, and are going to be removed altogether at some point in the future, so should be considered invalid syntax.
So with this in mind, the error describes the problem- your query has 7 placeholders, but you only pass 4 values. For the repeated values, you just need to repeat them where you pass the substitutions. |
288,381 | <p>I need to remove description textarea from a custom taxonomy edit screen in admin.</p>
<p>I'm actually doing this with the following jQuery line</p>
<pre><code>$('.form-field.term-description-wrap').remove();
</code></pre>
<p>but I would like doing it in PHP. Is it possible?</p>
<p>I'm looking at the <strong>{$taxonomy}_edit_form_fields</strong> hook. Is this the right one? If so which lines of code should I add into the callback function?</p>
| [
{
"answer_id": 288382,
"author": "Jacob Peattie",
"author_id": 39152,
"author_profile": "https://wordpress.stackexchange.com/users/39152",
"pm_score": 0,
"selected": false,
"text": "<p>It's not possible, there's no hook. The hook you mentioned is an <em>action</em>, not a filter, and can just be used to add fields or perform actions after the existing form fields are output, not modify existing fields/output.</p>\n"
},
{
"answer_id": 288385,
"author": "Levi Dulstein",
"author_id": 101988,
"author_profile": "https://wordpress.stackexchange.com/users/101988",
"pm_score": 1,
"selected": false,
"text": "<p>check out <a href=\"https://wordpress.stackexchange.com/questions/56569/remove-the-category-taxonomy-description-field\">this thread</a> - I'm afraid nothing has changed since then, there is still no way of filtering the description field (it's just html hardcoded in the file <a href=\"https://github.com/WordPress/WordPress/blob/master/wp-admin/edit-tags.php#L484\" rel=\"nofollow noreferrer\">https://github.com/WordPress/WordPress/blob/master/wp-admin/edit-tags.php#L484</a>, so you can't remove it with php without editing the core files, which is <strong>never</strong> a right way to go).</p>\n\n<p>The hook you're using, <code>{$taxonomy}_edit_form_fields</code> is fired on single term edit screen before the standard fields are printed, so you can use it to add something more, but not for filtering standard fields. </p>\n\n<p>I'd say you need to hold on to your JS solution for now or even better - go with CSS <code>display: none;</code> solution to make sure the field doesn't show up when JavaScript is disabled and to avoid flickering, like mentioned <a href=\"https://wordpress.stackexchange.com/questions/56569/remove-the-category-taxonomy-description-field/182652#182652\">here</a>.</p>\n"
}
]
| 2017/12/12 | [
"https://wordpress.stackexchange.com/questions/288381",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/85556/"
]
| I need to remove description textarea from a custom taxonomy edit screen in admin.
I'm actually doing this with the following jQuery line
```
$('.form-field.term-description-wrap').remove();
```
but I would like doing it in PHP. Is it possible?
I'm looking at the **{$taxonomy}\_edit\_form\_fields** hook. Is this the right one? If so which lines of code should I add into the callback function? | check out [this thread](https://wordpress.stackexchange.com/questions/56569/remove-the-category-taxonomy-description-field) - I'm afraid nothing has changed since then, there is still no way of filtering the description field (it's just html hardcoded in the file <https://github.com/WordPress/WordPress/blob/master/wp-admin/edit-tags.php#L484>, so you can't remove it with php without editing the core files, which is **never** a right way to go).
The hook you're using, `{$taxonomy}_edit_form_fields` is fired on single term edit screen before the standard fields are printed, so you can use it to add something more, but not for filtering standard fields.
I'd say you need to hold on to your JS solution for now or even better - go with CSS `display: none;` solution to make sure the field doesn't show up when JavaScript is disabled and to avoid flickering, like mentioned [here](https://wordpress.stackexchange.com/questions/56569/remove-the-category-taxonomy-description-field/182652#182652). |
288,391 | <p>So I was asked to add some analytics code to a sponsored post. I usually do it like this:</p>
<pre><code>if(is_single('post_slug')):
// Insert analytics code;
endif;
</code></pre>
<p>However, I cannot figure out how to do it on a post with a custom post type.</p>
<p>I found this function which takes the slug of the custom post type:</p>
<p>is_singular('event');</p>
<p>My question is, is there a function that would take the custom post type and the slug of the post?</p>
<p>Would really appreciate your help. Thanks!</p>
| [
{
"answer_id": 288398,
"author": "kierzniak",
"author_id": 132363,
"author_profile": "https://wordpress.stackexchange.com/users/132363",
"pm_score": 1,
"selected": false,
"text": "<p>You can mix two functions:</p>\n\n<pre><code>if( is_singular( $post_type ) && is_single( $post_slug ) ):\n// Insert analytics code;\nendif;\n</code></pre>\n"
},
{
"answer_id": 288415,
"author": "hamdirizal",
"author_id": 133145,
"author_profile": "https://wordpress.stackexchange.com/users/133145",
"pm_score": 0,
"selected": false,
"text": "<p>Use shortcode!</p>\n\n<p>Put this inside functions.php</p>\n\n<pre><code>// Assign the tag for our shortcode and identify the function that will run. \nadd_shortcode( 'custom-analytic', 'wpse61170_custom_analytic' );\n\n// Define function \nfunction wpse61170_custom_analytic() {\n ob_start();\n ?>\n //Put your analytics code here\n <?php\n return ob_get_clean();\n}\n</code></pre>\n\n<p>In any page you want the analytics to show, just put this shortcode </p>\n\n<pre><code>[custom-analytic]\n</code></pre>\n"
}
]
| 2017/12/12 | [
"https://wordpress.stackexchange.com/questions/288391",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/133129/"
]
| So I was asked to add some analytics code to a sponsored post. I usually do it like this:
```
if(is_single('post_slug')):
// Insert analytics code;
endif;
```
However, I cannot figure out how to do it on a post with a custom post type.
I found this function which takes the slug of the custom post type:
is\_singular('event');
My question is, is there a function that would take the custom post type and the slug of the post?
Would really appreciate your help. Thanks! | You can mix two functions:
```
if( is_singular( $post_type ) && is_single( $post_slug ) ):
// Insert analytics code;
endif;
``` |
288,407 | <p>I added post_meta 'batch' to 'assignment' custom post as follows:</p>
<pre><code>update_post_meta( $id, 'batch', strip_tags($_POST['batch']));
</code></pre>
<p>Now I am trying to retrieve this data as follows:</p>
<pre><code>$args = array(
'post_type' => 'assignment',
'post_status' => 'publish',
);
$assignments = new WP_Query( $args );
</code></pre>
<p>I want to get all data having 'batch=2017'. How can I do this? </p>
| [
{
"answer_id": 288398,
"author": "kierzniak",
"author_id": 132363,
"author_profile": "https://wordpress.stackexchange.com/users/132363",
"pm_score": 1,
"selected": false,
"text": "<p>You can mix two functions:</p>\n\n<pre><code>if( is_singular( $post_type ) && is_single( $post_slug ) ):\n// Insert analytics code;\nendif;\n</code></pre>\n"
},
{
"answer_id": 288415,
"author": "hamdirizal",
"author_id": 133145,
"author_profile": "https://wordpress.stackexchange.com/users/133145",
"pm_score": 0,
"selected": false,
"text": "<p>Use shortcode!</p>\n\n<p>Put this inside functions.php</p>\n\n<pre><code>// Assign the tag for our shortcode and identify the function that will run. \nadd_shortcode( 'custom-analytic', 'wpse61170_custom_analytic' );\n\n// Define function \nfunction wpse61170_custom_analytic() {\n ob_start();\n ?>\n //Put your analytics code here\n <?php\n return ob_get_clean();\n}\n</code></pre>\n\n<p>In any page you want the analytics to show, just put this shortcode </p>\n\n<pre><code>[custom-analytic]\n</code></pre>\n"
}
]
| 2017/12/12 | [
"https://wordpress.stackexchange.com/questions/288407",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/120824/"
]
| I added post\_meta 'batch' to 'assignment' custom post as follows:
```
update_post_meta( $id, 'batch', strip_tags($_POST['batch']));
```
Now I am trying to retrieve this data as follows:
```
$args = array(
'post_type' => 'assignment',
'post_status' => 'publish',
);
$assignments = new WP_Query( $args );
```
I want to get all data having 'batch=2017'. How can I do this? | You can mix two functions:
```
if( is_singular( $post_type ) && is_single( $post_slug ) ):
// Insert analytics code;
endif;
``` |
288,416 | <p>How do I retrieve the IDs of unattached media in my post?</p>
<p>I have two posts: <strong>POST A</strong> and <strong>POST B</strong> and a PDF file called <strong>file.pdf</strong>.</p>
<p>I've uploaded <strong>file.pdf</strong> to <strong>POST A</strong> but then also inserted it in <strong>POST B</strong>.</p>
<p>Now the <strong>file.pdf</strong> is still attached to <strong>POST A</strong> so I'm not able to get it's ID by using <code>get_attached_media( '', $post_B_id )</code>. </p>
<p>How can i retrieve the list of all media used in <strong>POST B</strong>, including files such as my file.pdf - not attached, by inserted into <strong>POST B</strong>?</p>
| [
{
"answer_id": 288421,
"author": "bueltge",
"author_id": 170,
"author_profile": "https://wordpress.stackexchange.com/users/170",
"pm_score": 0,
"selected": false,
"text": "<p>it is not easy to get an short hint, source code to find all usages of an media file. WordPress creates an relationship for an usage to a post type. But you have also the chance to use a media file inside a gallery, plugins, themes, custom code and more.</p>\n\n<h1>Core, inside back end</h1>\n\n<p>The default of the WordPress core have one option in the back end, inside the Media area. Select all 'unattached' files and you get an list.\n<a href=\"https://i.stack.imgur.com/hvYrI.png\" rel=\"nofollow noreferrer\"><img src=\"https://i.stack.imgur.com/hvYrI.png\" alt=\"enter image description here\"></a></p>\n\n<h1>Alternative plugin</h1>\n\n<p>However you should use the core solution above or think about usage of an plugin, that check all this dependencies, like <a href=\"https://wordpress.org/plugins/media-cleaner/\" rel=\"nofollow noreferrer\">Media Cleaner</a>. I don't have use this plugin, but it checks several usage of an media file and give you an overview about your media files.</p>\n"
},
{
"answer_id": 288432,
"author": "David Sword",
"author_id": 132362,
"author_profile": "https://wordpress.stackexchange.com/users/132362",
"pm_score": 2,
"selected": false,
"text": "<p>You can run a function like so to find and extract your media within a post</p>\n\n<pre><code>add_action('the_content', function($content) {\n $mediaRegex = \"/(src|href)=\\\"(.+?).(jpg|png|pdf)\\\"/i\";\n $mediaFind = preg_match_all($mediaRegex, $content, $media);\n if (isset(οΏΌ$media[2]) && count(οΏΌ$media[2]) > 0)\n $content = \"<pre>MEDIA WITHIN THIS PAGE: \\n\".print_r(οΏΌ$media[2],true).\"</pre>\".$content;\n return $content;\n});\n</code></pre>\n\n<p>You can modify the regex pattern to better suit your setup. You can make the regex take classnames of inserted media (instead of urls) and retrieve the attachment ID's that way.</p>\n\n<p>And/or if you want to further refine the media found, ensuring it's in your media library, you can put the media items URLs from your library in a array:</p>\n\n<pre><code>// get the media library for comparison\n$library = array();\n$args = array( \n 'post_type' => 'attachment',\n //'post_mime_type' => 'image', // if theres only one\n 'numberposts' => -1,\n 'post_status' => null,\n 'post_parent' => null,\n);\n$attachments = get_posts($args);\nforeach ($attachments as $post)\n $library[] = wp_get_attachment_url($post->ID);\n</code></pre>\n\n<p>Then write some code to argue with something like <code>in_array()</code> for individual <code>$media[2]</code> matches vs <code>$library</code>. Depending on use, you may want to add <a href=\"https://codex.wordpress.org/Transients_API\" rel=\"nofollow noreferrer\">Wordpress Transients</a> and wrap the library snippet.</p>\n"
},
{
"answer_id": 288433,
"author": "Tom J Nowell",
"author_id": 736,
"author_profile": "https://wordpress.stackexchange.com/users/736",
"pm_score": 3,
"selected": true,
"text": "<p>Yes you can do this! Is it simple/easy? Sort of... Is it fast and scalable? Oh dear god no .</p>\n\n<h2>The Super Expensive Solution</h2>\n\n<p>The solution here is this function:</p>\n\n<pre><code>$post_id = url_to_postid( $url );\n</code></pre>\n\n<p>The problem is that this is a very slow function that's expensive to call. If you call this when displaying every post, your DB server will be under super high strain and may fall over unless you configure it correctly and put it on a dedicated machine.</p>\n\n<p><strong><em>Note:</strong> you can't call this function early, it has to be on the <code>setup_theme</code> hook or later, or it'll cause a fatal error to occur.</em></p>\n\n<p>With this function, we can pull out every URL in the posts content, and do a test to see if it begins with the URL of our site. If it does, we can check to see if it matches any of the attachments, and if it doesn't, then we know it's unattached and can use this function to grab a copy.</p>\n\n<p>How to retrieve all the URLs in a posts content is a topic or another question however. Testing if a URL is for an attached attachment is a simple if statement comparison in a loop ( foreach attached thing, check if its URL matches the URL we're testing )</p>\n\n<h2>Speeding Things Up</h2>\n\n<p>There are a few things that might mitigate the cost of this function:</p>\n\n<ul>\n<li>Run the process on the save and update posts hook and store the result in post meta</li>\n<li>Wrap the function in a caching layer to speed things up ( only effective if there's an object caching solution in place such as memcached, not as effective as the previous mechanism )\n-Use a less precise method written by Pippins plugins that uses a DB query. This will bypass caches and it's still expensive, but not as expensive as <code>url_to_postid</code>. It also only works with GUIDs, hence the accuracy trade off</li>\n</ul>\n\n<h2>An Even More Expensive Solution</h2>\n\n<p>Query all the attachments via <code>WP_Query</code> and load all of them into memory, then check each attachment 1 by 1 to see if they appear in your post.</p>\n\n<p>This is by far the slowest and most expensive way to do this:</p>\n\n<ul>\n<li>As you upload more media, you have to load more when doing the query, for any site with more than 30 or 40 attachments you're going to get out of memory fatal errors</li>\n<li>It's a heavy database operation, your DB has to send all of the attachments, and if you've got several people browsing at once, this will get very problematic</li>\n<li>It will never scale past 5-10 concurrent users, and that's if you're lucky</li>\n<li>It's slow, checking every attachment takes time</li>\n</ul>\n"
}
]
| 2017/12/12 | [
"https://wordpress.stackexchange.com/questions/288416",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/101988/"
]
| How do I retrieve the IDs of unattached media in my post?
I have two posts: **POST A** and **POST B** and a PDF file called **file.pdf**.
I've uploaded **file.pdf** to **POST A** but then also inserted it in **POST B**.
Now the **file.pdf** is still attached to **POST A** so I'm not able to get it's ID by using `get_attached_media( '', $post_B_id )`.
How can i retrieve the list of all media used in **POST B**, including files such as my file.pdf - not attached, by inserted into **POST B**? | Yes you can do this! Is it simple/easy? Sort of... Is it fast and scalable? Oh dear god no .
The Super Expensive Solution
----------------------------
The solution here is this function:
```
$post_id = url_to_postid( $url );
```
The problem is that this is a very slow function that's expensive to call. If you call this when displaying every post, your DB server will be under super high strain and may fall over unless you configure it correctly and put it on a dedicated machine.
***Note:*** you can't call this function early, it has to be on the `setup_theme` hook or later, or it'll cause a fatal error to occur.
With this function, we can pull out every URL in the posts content, and do a test to see if it begins with the URL of our site. If it does, we can check to see if it matches any of the attachments, and if it doesn't, then we know it's unattached and can use this function to grab a copy.
How to retrieve all the URLs in a posts content is a topic or another question however. Testing if a URL is for an attached attachment is a simple if statement comparison in a loop ( foreach attached thing, check if its URL matches the URL we're testing )
Speeding Things Up
------------------
There are a few things that might mitigate the cost of this function:
* Run the process on the save and update posts hook and store the result in post meta
* Wrap the function in a caching layer to speed things up ( only effective if there's an object caching solution in place such as memcached, not as effective as the previous mechanism )
-Use a less precise method written by Pippins plugins that uses a DB query. This will bypass caches and it's still expensive, but not as expensive as `url_to_postid`. It also only works with GUIDs, hence the accuracy trade off
An Even More Expensive Solution
-------------------------------
Query all the attachments via `WP_Query` and load all of them into memory, then check each attachment 1 by 1 to see if they appear in your post.
This is by far the slowest and most expensive way to do this:
* As you upload more media, you have to load more when doing the query, for any site with more than 30 or 40 attachments you're going to get out of memory fatal errors
* It's a heavy database operation, your DB has to send all of the attachments, and if you've got several people browsing at once, this will get very problematic
* It will never scale past 5-10 concurrent users, and that's if you're lucky
* It's slow, checking every attachment takes time |
288,434 | <p>When I embed a Youtube video onto my page, is there a way to change the thumbnail displayed (<a href="https://imgur.com/F4daH3U" rel="nofollow noreferrer">screenshot</a>)? I do not have admin access to the Youtube video in-question.</p>
<p>I would prefer a non-plugin solution if possible. I found <a href="http://wpdecoder.com/video-tutorials/custom-thumbnail-with-youtube-video/" rel="nofollow noreferrer">these instructions</a>, but they did not work.</p>
| [
{
"answer_id": 288436,
"author": "Nicolai Grossherr",
"author_id": 22534,
"author_profile": "https://wordpress.stackexchange.com/users/22534",
"pm_score": 3,
"selected": true,
"text": "<p>The <a href=\"https://codex.wordpress.org/Video_Shortcode\" rel=\"nofollow noreferrer\"><code>[video]</code> shortcode</a> can be used with the <code>src</code> being an URL of a youtube video. To set a placeholder, preview thumbnail use <code>poster</code>, it even works nicely via GUI. In the end it should look somewhat like the bellow example.</p>\n\n<pre><code>[video src=\"https://www.youtube.com/watch?v=XYZ\" poster=\"http://example.com/wp-content/uploads/2017/01/example.jpg\"]\n</code></pre>\n"
},
{
"answer_id": 372000,
"author": "dig99",
"author_id": 171719,
"author_profile": "https://wordpress.stackexchange.com/users/171719",
"pm_score": 0,
"selected": false,
"text": "<p>check this out, maybe this will help.</p>\n<pre><code>\n<div class="video-responsive"><iframe src="https://www.youtube-nocookie.com/embed/1Cz2Xzm6knM/videoseries?list=PLq-1Cz2Xzm6knM-1Cz2Xzm6knM&amp;rel=0" width="420" height="315" frameborder="0" allowfullscreen="allowfullscreen"></iframe></div>\n\n\n.video-responsive{\n overflow:hidden;\n padding-bottom:56.25%;\n position:relative;\n height:0;\n}\n.video-responsive iframe{\n left:0;\n top:0;\n height:100%;\n width:100%;\n position:absolute;\n}\n</code></pre>\n"
}
]
| 2017/12/12 | [
"https://wordpress.stackexchange.com/questions/288434",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/51204/"
]
| When I embed a Youtube video onto my page, is there a way to change the thumbnail displayed ([screenshot](https://imgur.com/F4daH3U))? I do not have admin access to the Youtube video in-question.
I would prefer a non-plugin solution if possible. I found [these instructions](http://wpdecoder.com/video-tutorials/custom-thumbnail-with-youtube-video/), but they did not work. | The [`[video]` shortcode](https://codex.wordpress.org/Video_Shortcode) can be used with the `src` being an URL of a youtube video. To set a placeholder, preview thumbnail use `poster`, it even works nicely via GUI. In the end it should look somewhat like the bellow example.
```
[video src="https://www.youtube.com/watch?v=XYZ" poster="http://example.com/wp-content/uploads/2017/01/example.jpg"]
``` |
288,463 | <p>I asked a question yesterday, but I realised that the code was not correct and it was my bad, so I refactored everything. I have a form with two fields which when user submits and takes a quiz test, gets registered and his scores saved to user meta data table. My user gets created, but when I want to add extra meta data of quiz scores for him using <code>update_user_meta</code> it just doesn't do anything. Here is my code:</p>
<pre><code> if (isset($_POST['submit_contact'])) {
$email = $_POST['email_contact'];
$full = $_POST['fullname_contact'];
$_SESSION["email"] = $email;
$_SESSION["name"] = $full;
echo $_SESSION["mail"];
}
function save_quiz_score() {
$score = $_POST['score'];
$email = $_SESSION["email"];
$username = $_SESSION["name"];
$user = get_user_by("email", $email);
register_new_user($email, $_SESSION["email"]);
update_user_meta($user, "quiz_scores", $score);
echo $_SESSION["mail"];
}
</code></pre>
<p>I'm using <code>session_start</code> and echo the sessions out and can see the emails, so that is no problem. <code>$_POST['score']</code> is also valid, because in the past I tried saving it on its own and it worked fine, so neither is that a problem. I just feel like I tried everything and feel like giving up. Maybe an extra pair of eyes can help me and notice a problem. Thanks in advance.</p>
| [
{
"answer_id": 288464,
"author": "Limpuls",
"author_id": 133005,
"author_profile": "https://wordpress.stackexchange.com/users/133005",
"pm_score": 2,
"selected": false,
"text": "<p>Solved the problem by changing these lines:</p>\n\n<pre><code>register_new_user($email, $_SESSION[\"email\"]);\nupdate_user_meta($user, \"quiz_scores\", $score);\n</code></pre>\n\n<p>To this:</p>\n\n<pre><code>$registered = register_new_user($email, $_SESSION[\"email\"]);\n update_user_meta($registered, \"quiz_scores\", $score);\n</code></pre>\n\n<p>In the first example, I was trying to get the user from database before actually registering it:</p>\n\n<pre><code>$user = get_user_by(\"email\", $email);\n</code></pre>\n\n<p>So using <code>$user</code> variable inside <code>update_user_meta()</code> just didn't work.</p>\n"
},
{
"answer_id": 288465,
"author": "Shibi",
"author_id": 62500,
"author_profile": "https://wordpress.stackexchange.com/users/62500",
"pm_score": 3,
"selected": true,
"text": "<p>You set the variable <code>$user</code> before you created this user..</p>\n\n<p>It should be like this and you need to check if the user already exists</p>\n\n<pre><code>$user = get_user_by(\"email\", $email); // Its return you the user object\nif($user) {\n update_user_meta($user->ID, \"quiz_scores\", $score);\n} else {\n $user_id = register_new_user($email, $_SESSION[\"email\"]);\n update_user_meta($user_id, \"quiz_scores\", $score);\n}\n</code></pre>\n"
}
]
| 2017/12/13 | [
"https://wordpress.stackexchange.com/questions/288463",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/133005/"
]
| I asked a question yesterday, but I realised that the code was not correct and it was my bad, so I refactored everything. I have a form with two fields which when user submits and takes a quiz test, gets registered and his scores saved to user meta data table. My user gets created, but when I want to add extra meta data of quiz scores for him using `update_user_meta` it just doesn't do anything. Here is my code:
```
if (isset($_POST['submit_contact'])) {
$email = $_POST['email_contact'];
$full = $_POST['fullname_contact'];
$_SESSION["email"] = $email;
$_SESSION["name"] = $full;
echo $_SESSION["mail"];
}
function save_quiz_score() {
$score = $_POST['score'];
$email = $_SESSION["email"];
$username = $_SESSION["name"];
$user = get_user_by("email", $email);
register_new_user($email, $_SESSION["email"]);
update_user_meta($user, "quiz_scores", $score);
echo $_SESSION["mail"];
}
```
I'm using `session_start` and echo the sessions out and can see the emails, so that is no problem. `$_POST['score']` is also valid, because in the past I tried saving it on its own and it worked fine, so neither is that a problem. I just feel like I tried everything and feel like giving up. Maybe an extra pair of eyes can help me and notice a problem. Thanks in advance. | You set the variable `$user` before you created this user..
It should be like this and you need to check if the user already exists
```
$user = get_user_by("email", $email); // Its return you the user object
if($user) {
update_user_meta($user->ID, "quiz_scores", $score);
} else {
$user_id = register_new_user($email, $_SESSION["email"]);
update_user_meta($user_id, "quiz_scores", $score);
}
``` |
288,486 | <p>I want to display 4 column footer menu. but when I add new menu the wp_nav_menu create a < li > and add every menu items to it.</p>
<p><a href="https://i.stack.imgur.com/Fw6do.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/Fw6do.png" alt="enter image description here"></a></p>
<p>now, how can I wrap every li element with a custom div tag with a class?</p>
<p>I need this output :</p>
<p><a href="https://i.stack.imgur.com/zQrnB.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/zQrnB.png" alt="enter image description here"></a></p>
<p>In the above image, you can see every menu is wrapped inside a div. </p>
<p>I tried with wp_nav_menu() it does not help. As I'm new to WordPress theme development I don't know more option.</p>
<p>Is there any way I can say WordPress to add a div element with a custom class to add before every menu item?</p>
<p>Thanks :)</p>
| [
{
"answer_id": 288464,
"author": "Limpuls",
"author_id": 133005,
"author_profile": "https://wordpress.stackexchange.com/users/133005",
"pm_score": 2,
"selected": false,
"text": "<p>Solved the problem by changing these lines:</p>\n\n<pre><code>register_new_user($email, $_SESSION[\"email\"]);\nupdate_user_meta($user, \"quiz_scores\", $score);\n</code></pre>\n\n<p>To this:</p>\n\n<pre><code>$registered = register_new_user($email, $_SESSION[\"email\"]);\n update_user_meta($registered, \"quiz_scores\", $score);\n</code></pre>\n\n<p>In the first example, I was trying to get the user from database before actually registering it:</p>\n\n<pre><code>$user = get_user_by(\"email\", $email);\n</code></pre>\n\n<p>So using <code>$user</code> variable inside <code>update_user_meta()</code> just didn't work.</p>\n"
},
{
"answer_id": 288465,
"author": "Shibi",
"author_id": 62500,
"author_profile": "https://wordpress.stackexchange.com/users/62500",
"pm_score": 3,
"selected": true,
"text": "<p>You set the variable <code>$user</code> before you created this user..</p>\n\n<p>It should be like this and you need to check if the user already exists</p>\n\n<pre><code>$user = get_user_by(\"email\", $email); // Its return you the user object\nif($user) {\n update_user_meta($user->ID, \"quiz_scores\", $score);\n} else {\n $user_id = register_new_user($email, $_SESSION[\"email\"]);\n update_user_meta($user_id, \"quiz_scores\", $score);\n}\n</code></pre>\n"
}
]
| 2017/12/13 | [
"https://wordpress.stackexchange.com/questions/288486",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/133193/"
]
| I want to display 4 column footer menu. but when I add new menu the wp\_nav\_menu create a < li > and add every menu items to it.
[](https://i.stack.imgur.com/Fw6do.png)
now, how can I wrap every li element with a custom div tag with a class?
I need this output :
[](https://i.stack.imgur.com/zQrnB.png)
In the above image, you can see every menu is wrapped inside a div.
I tried with wp\_nav\_menu() it does not help. As I'm new to WordPress theme development I don't know more option.
Is there any way I can say WordPress to add a div element with a custom class to add before every menu item?
Thanks :) | You set the variable `$user` before you created this user..
It should be like this and you need to check if the user already exists
```
$user = get_user_by("email", $email); // Its return you the user object
if($user) {
update_user_meta($user->ID, "quiz_scores", $score);
} else {
$user_id = register_new_user($email, $_SESSION["email"]);
update_user_meta($user_id, "quiz_scores", $score);
}
``` |
288,496 | <p>I want to force all user to access https (SSL) entire website.
I tried to set it at options-general.php page,I try to install a plug-in.
They are all success.But I can't enter or access all wp-admin page either.
The website will redirect to myaccount page when force to SSL is on.</p>
<p>how can i access admin page with ssl? what did i miss?</p>
| [
{
"answer_id": 288464,
"author": "Limpuls",
"author_id": 133005,
"author_profile": "https://wordpress.stackexchange.com/users/133005",
"pm_score": 2,
"selected": false,
"text": "<p>Solved the problem by changing these lines:</p>\n\n<pre><code>register_new_user($email, $_SESSION[\"email\"]);\nupdate_user_meta($user, \"quiz_scores\", $score);\n</code></pre>\n\n<p>To this:</p>\n\n<pre><code>$registered = register_new_user($email, $_SESSION[\"email\"]);\n update_user_meta($registered, \"quiz_scores\", $score);\n</code></pre>\n\n<p>In the first example, I was trying to get the user from database before actually registering it:</p>\n\n<pre><code>$user = get_user_by(\"email\", $email);\n</code></pre>\n\n<p>So using <code>$user</code> variable inside <code>update_user_meta()</code> just didn't work.</p>\n"
},
{
"answer_id": 288465,
"author": "Shibi",
"author_id": 62500,
"author_profile": "https://wordpress.stackexchange.com/users/62500",
"pm_score": 3,
"selected": true,
"text": "<p>You set the variable <code>$user</code> before you created this user..</p>\n\n<p>It should be like this and you need to check if the user already exists</p>\n\n<pre><code>$user = get_user_by(\"email\", $email); // Its return you the user object\nif($user) {\n update_user_meta($user->ID, \"quiz_scores\", $score);\n} else {\n $user_id = register_new_user($email, $_SESSION[\"email\"]);\n update_user_meta($user_id, \"quiz_scores\", $score);\n}\n</code></pre>\n"
}
]
| 2017/12/13 | [
"https://wordpress.stackexchange.com/questions/288496",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/133200/"
]
| I want to force all user to access https (SSL) entire website.
I tried to set it at options-general.php page,I try to install a plug-in.
They are all success.But I can't enter or access all wp-admin page either.
The website will redirect to myaccount page when force to SSL is on.
how can i access admin page with ssl? what did i miss? | You set the variable `$user` before you created this user..
It should be like this and you need to check if the user already exists
```
$user = get_user_by("email", $email); // Its return you the user object
if($user) {
update_user_meta($user->ID, "quiz_scores", $score);
} else {
$user_id = register_new_user($email, $_SESSION["email"]);
update_user_meta($user_id, "quiz_scores", $score);
}
``` |
288,504 | <p>Is it possible to rewrite this kind of action url on all the posts of a custom post type?</p>
<p><strong>Original url:</strong></p>
<pre><code>example.com/custompostype/post-title/?action=play-123
</code></pre>
<p>(Desired Output) <strong>Rewriting to:</strong></p>
<pre><code>example.com/custompostype/post-title/play-123
</code></pre>
<p>123 = <strong>postid</strong></p>
<p>Is it possible to do it with wordpress's functions instead of direct .htaccess edit?</p>
| [
{
"answer_id": 288505,
"author": "Sid",
"author_id": 110516,
"author_profile": "https://wordpress.stackexchange.com/users/110516",
"pm_score": -1,
"selected": false,
"text": "<p>Assuming that you have the page (new URL) already functional, use this:</p>\n\n<pre><code>$current_url=\"//\".$_SERVER['HTTP_HOST'].$_SERVER['REQUEST_URI'];\n\nif(strpos($current_url, '?action=')) {\n $action = $_GET['action'];\n wp_redirect( 'example.com/custompostype/post-title/' . $action, $status = 301 );\n exit;\n}\n</code></pre>\n"
},
{
"answer_id": 288523,
"author": "brianjohnhanna",
"author_id": 65403,
"author_profile": "https://wordpress.stackexchange.com/users/65403",
"pm_score": 0,
"selected": false,
"text": "<p>I'm pretty sure if you need to use the <code>action</code> parameter you will have some mixed results, as this is one WordPress uses under the hood for a lot of things. If you have flexibility over the name of the parameter, this is indeed possible. I am unable to test this at the moment but this should get you headed in the right direction.</p>\n\n<pre><code>function wpse_cpt_rewrite_rule() {\n add_rewrite_rule('^customposttype/([^/]*)/([^/]*)/?','index.php?pagename=$matches[1]&action=$matches[2]','top');\n}\nadd_action('init', 'wpse_cpt_rewrite_rule', 10, 0);\n</code></pre>\n\n<p>It should be noted that if you don't use the <code>action</code> parameter, you'll need to register your custom param like so as well.</p>\n\n<pre><code>function wpse_add_custom_tag() {\n add_rewrite_tag('%my_custom_action%', '([^&]+)');\n}\nadd_action('init', 'wpse_add_custom_tag', 10, 0);\n</code></pre>\n"
},
{
"answer_id": 288585,
"author": "Amenadiel17",
"author_id": 133205,
"author_profile": "https://wordpress.stackexchange.com/users/133205",
"pm_score": 1,
"selected": false,
"text": "<p>I just realized i used different kind of rewriting which didn't require @Jacob's codes (using add_rewrite_endpoint)</p>\n\n<pre><code>add_action('init', 'wpse42279_add_endpoints');\nfunction wpse42279_add_endpoints()\n{\n add_rewrite_endpoint('play', EP_PERMALINK);\n}\n</code></pre>\n\n<p>And then i used this conditionals on the single page:</p>\n\n<pre><code>global $post;\n$pid = $post->ID;\n$var = get_query_var( 'play' ); \nif( !empty($var) and $var == $pid) :\n// do stuff\nendif;\n</code></pre>\n\n<p><strong>Now here's the working pretty link:</strong></p>\n\n<pre><code>example.com/custompostype/post-title/play/123/\n</code></pre>\n\n<p><strong>Instead of:</strong>\nexample.com/custompostype/post-title/?play=123</p>\n\n<p>However the problem now is that the old url still exist (example.com/custompostype/post-title/?play=123) and still accessible/visible. Is it possible to make it work like how this code works: </p>\n\n<pre><code>example.com/?custompostype=321\n</code></pre>\n\n<p>(It redirects to the pretty link: example.com/custompostype/post-title/)</p>\n"
}
]
| 2017/12/13 | [
"https://wordpress.stackexchange.com/questions/288504",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/133205/"
]
| Is it possible to rewrite this kind of action url on all the posts of a custom post type?
**Original url:**
```
example.com/custompostype/post-title/?action=play-123
```
(Desired Output) **Rewriting to:**
```
example.com/custompostype/post-title/play-123
```
123 = **postid**
Is it possible to do it with wordpress's functions instead of direct .htaccess edit? | I just realized i used different kind of rewriting which didn't require @Jacob's codes (using add\_rewrite\_endpoint)
```
add_action('init', 'wpse42279_add_endpoints');
function wpse42279_add_endpoints()
{
add_rewrite_endpoint('play', EP_PERMALINK);
}
```
And then i used this conditionals on the single page:
```
global $post;
$pid = $post->ID;
$var = get_query_var( 'play' );
if( !empty($var) and $var == $pid) :
// do stuff
endif;
```
**Now here's the working pretty link:**
```
example.com/custompostype/post-title/play/123/
```
**Instead of:**
example.com/custompostype/post-title/?play=123
However the problem now is that the old url still exist (example.com/custompostype/post-title/?play=123) and still accessible/visible. Is it possible to make it work like how this code works:
```
example.com/?custompostype=321
```
(It redirects to the pretty link: example.com/custompostype/post-title/) |
288,530 | <p>All in <em>single.php</em> file in <em>Genesis child theme</em>.</p>
<p>I have an <code>echo</code> of <code>divs</code> and in between I in one of the <code>anchors</code> I am trying to insert author's post url via a <code>variable</code>, like so:</p>
<pre><code>function my_function() {
$author = get_the_author_meta( $post->post_author );
$author_link = get_author_posts_url($author);
$author_avatar = get_avatar_url(get_the_author_meta( $post->post_author ));
$featured_image = wp_get_attachment_image_src( get_post_thumbnail_id( $post->ID ), 'full' );
//..
echo '<div>
// ..
<div class="">
By <a href="'.$author_link.'">Author</a>
</div>'
</div>
}
genesis();
</code></pre>
<p>I have tried:
<code>the_author_posts_url();</code>,
<code>get_the_author_meta('user_url');</code>,
<code>get_author_posts_url();</code>, <code>get_author_posts_url( get_the_author_meta( 'ID' ) );</code>
every time the link is either empty or it generates </p>
<pre><code>http://localhost/author
</code></pre>
<p>without outputting the specific author.</p>
<p>full code of single.php is here:</p>
<p>
<p>function custom_entry_content() {
$author = get_the_author_meta( $post->post_author );</p>
<pre><code>$author_link = get_author_posts_url($author);
$author_avatar = get_avatar_url(get_the_author_meta( $post->post_author ));
$featured_image = wp_get_attachment_image_src( get_post_thumbnail_id( $post->ID ), 'full' );
echo '<div style="margin-bottom: 50px;position: relative; text-align:center; width:100%;background-image: url('.$featured_image[0].');
height: 502px; background-size: cover;
background-repeat: no-repeat;">
<div class="post-title-box">
<h1 class="the-title">
'. get_the_title(). '</h1>
</div>
<div class="post-auth-info">
<div class="vertical-middle" style="display:inline-block">
<div class="">
By <a href="'.$author_link.'">Author</a>
</div>
<time class="mk-publish-date" datetime="2017-11-01">
<a href="#">Published ' . time_elapsed_string(get_the_date()). '</a>
</time>
</div>
<div style="display:inline-block">
<a href="'.$author_link.'">
<div>
<img alt="" src="'.$author_avatar.'" class="img-circle avatar avatar-55 " height="55" width="55" style="height:55px;width:55px">
</div>
</a>
</div>
</div>
</div>';
}
// Removes Published by and time data from before the post content area
remove_action( 'genesis_entry_header', 'genesis_post_info', 12);
add_filter( 'genesis_attr_site-inner', 'remove_top_padding');
function remove_top_padding( $attributes ) {
$attributes['class'] = 'container box nopadding';
return $attributes;
}
// Adds left padding to content
add_filter( 'genesis_attr_content', 'padding_left');
function padding_left( $attributes ) {
if ( 'full-width-content' === genesis_site_layout() )
$attributes['class'] = '';
else
$attributes['class'] = 'col-md-8 single-post-entry';
return $attributes;
}
genesis();
</code></pre>
<p>Many thanks in advance!</p>
| [
{
"answer_id": 288505,
"author": "Sid",
"author_id": 110516,
"author_profile": "https://wordpress.stackexchange.com/users/110516",
"pm_score": -1,
"selected": false,
"text": "<p>Assuming that you have the page (new URL) already functional, use this:</p>\n\n<pre><code>$current_url=\"//\".$_SERVER['HTTP_HOST'].$_SERVER['REQUEST_URI'];\n\nif(strpos($current_url, '?action=')) {\n $action = $_GET['action'];\n wp_redirect( 'example.com/custompostype/post-title/' . $action, $status = 301 );\n exit;\n}\n</code></pre>\n"
},
{
"answer_id": 288523,
"author": "brianjohnhanna",
"author_id": 65403,
"author_profile": "https://wordpress.stackexchange.com/users/65403",
"pm_score": 0,
"selected": false,
"text": "<p>I'm pretty sure if you need to use the <code>action</code> parameter you will have some mixed results, as this is one WordPress uses under the hood for a lot of things. If you have flexibility over the name of the parameter, this is indeed possible. I am unable to test this at the moment but this should get you headed in the right direction.</p>\n\n<pre><code>function wpse_cpt_rewrite_rule() {\n add_rewrite_rule('^customposttype/([^/]*)/([^/]*)/?','index.php?pagename=$matches[1]&action=$matches[2]','top');\n}\nadd_action('init', 'wpse_cpt_rewrite_rule', 10, 0);\n</code></pre>\n\n<p>It should be noted that if you don't use the <code>action</code> parameter, you'll need to register your custom param like so as well.</p>\n\n<pre><code>function wpse_add_custom_tag() {\n add_rewrite_tag('%my_custom_action%', '([^&]+)');\n}\nadd_action('init', 'wpse_add_custom_tag', 10, 0);\n</code></pre>\n"
},
{
"answer_id": 288585,
"author": "Amenadiel17",
"author_id": 133205,
"author_profile": "https://wordpress.stackexchange.com/users/133205",
"pm_score": 1,
"selected": false,
"text": "<p>I just realized i used different kind of rewriting which didn't require @Jacob's codes (using add_rewrite_endpoint)</p>\n\n<pre><code>add_action('init', 'wpse42279_add_endpoints');\nfunction wpse42279_add_endpoints()\n{\n add_rewrite_endpoint('play', EP_PERMALINK);\n}\n</code></pre>\n\n<p>And then i used this conditionals on the single page:</p>\n\n<pre><code>global $post;\n$pid = $post->ID;\n$var = get_query_var( 'play' ); \nif( !empty($var) and $var == $pid) :\n// do stuff\nendif;\n</code></pre>\n\n<p><strong>Now here's the working pretty link:</strong></p>\n\n<pre><code>example.com/custompostype/post-title/play/123/\n</code></pre>\n\n<p><strong>Instead of:</strong>\nexample.com/custompostype/post-title/?play=123</p>\n\n<p>However the problem now is that the old url still exist (example.com/custompostype/post-title/?play=123) and still accessible/visible. Is it possible to make it work like how this code works: </p>\n\n<pre><code>example.com/?custompostype=321\n</code></pre>\n\n<p>(It redirects to the pretty link: example.com/custompostype/post-title/)</p>\n"
}
]
| 2017/12/13 | [
"https://wordpress.stackexchange.com/questions/288530",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/103078/"
]
| All in *single.php* file in *Genesis child theme*.
I have an `echo` of `divs` and in between I in one of the `anchors` I am trying to insert author's post url via a `variable`, like so:
```
function my_function() {
$author = get_the_author_meta( $post->post_author );
$author_link = get_author_posts_url($author);
$author_avatar = get_avatar_url(get_the_author_meta( $post->post_author ));
$featured_image = wp_get_attachment_image_src( get_post_thumbnail_id( $post->ID ), 'full' );
//..
echo '<div>
// ..
<div class="">
By <a href="'.$author_link.'">Author</a>
</div>'
</div>
}
genesis();
```
I have tried:
`the_author_posts_url();`,
`get_the_author_meta('user_url');`,
`get_author_posts_url();`, `get_author_posts_url( get_the_author_meta( 'ID' ) );`
every time the link is either empty or it generates
```
http://localhost/author
```
without outputting the specific author.
full code of single.php is here:
function custom\_entry\_content() {
$author = get\_the\_author\_meta( $post->post\_author );
```
$author_link = get_author_posts_url($author);
$author_avatar = get_avatar_url(get_the_author_meta( $post->post_author ));
$featured_image = wp_get_attachment_image_src( get_post_thumbnail_id( $post->ID ), 'full' );
echo '<div style="margin-bottom: 50px;position: relative; text-align:center; width:100%;background-image: url('.$featured_image[0].');
height: 502px; background-size: cover;
background-repeat: no-repeat;">
<div class="post-title-box">
<h1 class="the-title">
'. get_the_title(). '</h1>
</div>
<div class="post-auth-info">
<div class="vertical-middle" style="display:inline-block">
<div class="">
By <a href="'.$author_link.'">Author</a>
</div>
<time class="mk-publish-date" datetime="2017-11-01">
<a href="#">Published ' . time_elapsed_string(get_the_date()). '</a>
</time>
</div>
<div style="display:inline-block">
<a href="'.$author_link.'">
<div>
<img alt="" src="'.$author_avatar.'" class="img-circle avatar avatar-55 " height="55" width="55" style="height:55px;width:55px">
</div>
</a>
</div>
</div>
</div>';
}
// Removes Published by and time data from before the post content area
remove_action( 'genesis_entry_header', 'genesis_post_info', 12);
add_filter( 'genesis_attr_site-inner', 'remove_top_padding');
function remove_top_padding( $attributes ) {
$attributes['class'] = 'container box nopadding';
return $attributes;
}
// Adds left padding to content
add_filter( 'genesis_attr_content', 'padding_left');
function padding_left( $attributes ) {
if ( 'full-width-content' === genesis_site_layout() )
$attributes['class'] = '';
else
$attributes['class'] = 'col-md-8 single-post-entry';
return $attributes;
}
genesis();
```
Many thanks in advance! | I just realized i used different kind of rewriting which didn't require @Jacob's codes (using add\_rewrite\_endpoint)
```
add_action('init', 'wpse42279_add_endpoints');
function wpse42279_add_endpoints()
{
add_rewrite_endpoint('play', EP_PERMALINK);
}
```
And then i used this conditionals on the single page:
```
global $post;
$pid = $post->ID;
$var = get_query_var( 'play' );
if( !empty($var) and $var == $pid) :
// do stuff
endif;
```
**Now here's the working pretty link:**
```
example.com/custompostype/post-title/play/123/
```
**Instead of:**
example.com/custompostype/post-title/?play=123
However the problem now is that the old url still exist (example.com/custompostype/post-title/?play=123) and still accessible/visible. Is it possible to make it work like how this code works:
```
example.com/?custompostype=321
```
(It redirects to the pretty link: example.com/custompostype/post-title/) |
288,538 | <p>The problem is simple, the solution doesn't want to meet me. I want to display (echo) the percentage of the VAT I have defined in my woocommerce settings. Let's say it is 24%. I want to echo it (in the cart or checkout page somewhere, it doesn't really matter) as 0.24 . If I change the VAT to 22%, then automatically it should show 0.22 and so on... How can I achieve this?
Many thanks in advance</p>
| [
{
"answer_id": 288505,
"author": "Sid",
"author_id": 110516,
"author_profile": "https://wordpress.stackexchange.com/users/110516",
"pm_score": -1,
"selected": false,
"text": "<p>Assuming that you have the page (new URL) already functional, use this:</p>\n\n<pre><code>$current_url=\"//\".$_SERVER['HTTP_HOST'].$_SERVER['REQUEST_URI'];\n\nif(strpos($current_url, '?action=')) {\n $action = $_GET['action'];\n wp_redirect( 'example.com/custompostype/post-title/' . $action, $status = 301 );\n exit;\n}\n</code></pre>\n"
},
{
"answer_id": 288523,
"author": "brianjohnhanna",
"author_id": 65403,
"author_profile": "https://wordpress.stackexchange.com/users/65403",
"pm_score": 0,
"selected": false,
"text": "<p>I'm pretty sure if you need to use the <code>action</code> parameter you will have some mixed results, as this is one WordPress uses under the hood for a lot of things. If you have flexibility over the name of the parameter, this is indeed possible. I am unable to test this at the moment but this should get you headed in the right direction.</p>\n\n<pre><code>function wpse_cpt_rewrite_rule() {\n add_rewrite_rule('^customposttype/([^/]*)/([^/]*)/?','index.php?pagename=$matches[1]&action=$matches[2]','top');\n}\nadd_action('init', 'wpse_cpt_rewrite_rule', 10, 0);\n</code></pre>\n\n<p>It should be noted that if you don't use the <code>action</code> parameter, you'll need to register your custom param like so as well.</p>\n\n<pre><code>function wpse_add_custom_tag() {\n add_rewrite_tag('%my_custom_action%', '([^&]+)');\n}\nadd_action('init', 'wpse_add_custom_tag', 10, 0);\n</code></pre>\n"
},
{
"answer_id": 288585,
"author": "Amenadiel17",
"author_id": 133205,
"author_profile": "https://wordpress.stackexchange.com/users/133205",
"pm_score": 1,
"selected": false,
"text": "<p>I just realized i used different kind of rewriting which didn't require @Jacob's codes (using add_rewrite_endpoint)</p>\n\n<pre><code>add_action('init', 'wpse42279_add_endpoints');\nfunction wpse42279_add_endpoints()\n{\n add_rewrite_endpoint('play', EP_PERMALINK);\n}\n</code></pre>\n\n<p>And then i used this conditionals on the single page:</p>\n\n<pre><code>global $post;\n$pid = $post->ID;\n$var = get_query_var( 'play' ); \nif( !empty($var) and $var == $pid) :\n// do stuff\nendif;\n</code></pre>\n\n<p><strong>Now here's the working pretty link:</strong></p>\n\n<pre><code>example.com/custompostype/post-title/play/123/\n</code></pre>\n\n<p><strong>Instead of:</strong>\nexample.com/custompostype/post-title/?play=123</p>\n\n<p>However the problem now is that the old url still exist (example.com/custompostype/post-title/?play=123) and still accessible/visible. Is it possible to make it work like how this code works: </p>\n\n<pre><code>example.com/?custompostype=321\n</code></pre>\n\n<p>(It redirects to the pretty link: example.com/custompostype/post-title/)</p>\n"
}
]
| 2017/12/13 | [
"https://wordpress.stackexchange.com/questions/288538",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/80225/"
]
| The problem is simple, the solution doesn't want to meet me. I want to display (echo) the percentage of the VAT I have defined in my woocommerce settings. Let's say it is 24%. I want to echo it (in the cart or checkout page somewhere, it doesn't really matter) as 0.24 . If I change the VAT to 22%, then automatically it should show 0.22 and so on... How can I achieve this?
Many thanks in advance | I just realized i used different kind of rewriting which didn't require @Jacob's codes (using add\_rewrite\_endpoint)
```
add_action('init', 'wpse42279_add_endpoints');
function wpse42279_add_endpoints()
{
add_rewrite_endpoint('play', EP_PERMALINK);
}
```
And then i used this conditionals on the single page:
```
global $post;
$pid = $post->ID;
$var = get_query_var( 'play' );
if( !empty($var) and $var == $pid) :
// do stuff
endif;
```
**Now here's the working pretty link:**
```
example.com/custompostype/post-title/play/123/
```
**Instead of:**
example.com/custompostype/post-title/?play=123
However the problem now is that the old url still exist (example.com/custompostype/post-title/?play=123) and still accessible/visible. Is it possible to make it work like how this code works:
```
example.com/?custompostype=321
```
(It redirects to the pretty link: example.com/custompostype/post-title/) |
288,540 | <p>I am creating a membership site where I am trying to login a particular user from a link sent to their email address.</p>
<p>I have a custom post typed called "Members", where I have stored a unique key with the name "user_key". After a particular process, the email is sent to that user with an auto login link.</p>
<p>An example link looks like the following</p>
<p><a href="http://example.com/process/?key=DcP2K7cmBUrLVRjizs78RAuuoMGRFc6F6TMDm6E6" rel="nofollow noreferrer">http://example.com/process/?key=DcP2K7cmBUrLVRjizs78RAuuoMGRFc6F6TMDm6E6</a></p>
<p>Process is the page which handles the login part. Here is the code used in that page.</p>
<pre><code>get_header();
$key = $_GET['key'];
$args = array(
'post_type' => 'member',
'meta_value' => $key
);
$properties = new WP_Query($args);
if($properties->have_posts()) :
while($properties->have_posts()) : $properties->the_post();
$author = $post->post_author;
$user = get_user_by('ID', $author);
$user_id = $user->ID;
echo $user_id;
wp_set_current_user($user_id, $loginusername);
wp_set_auth_cookie($user_id);
do_action('wp_login', $loginusername);
wp_redirect( home_url() );
endwhile;
endif;
wp_reset_query();
get_footer();
</code></pre>
<p>When I go to that particular link, I get the following error.</p>
<p>"Warning: Cannot modify header information - headers already sent"</p>
<p>From what I understand, I think it's the "wp_set_auth_cookie" part which is done after the headers are loaded, which is creating that problem.</p>
<p>Anyone has any ideas how to fix it?</p>
| [
{
"answer_id": 288505,
"author": "Sid",
"author_id": 110516,
"author_profile": "https://wordpress.stackexchange.com/users/110516",
"pm_score": -1,
"selected": false,
"text": "<p>Assuming that you have the page (new URL) already functional, use this:</p>\n\n<pre><code>$current_url=\"//\".$_SERVER['HTTP_HOST'].$_SERVER['REQUEST_URI'];\n\nif(strpos($current_url, '?action=')) {\n $action = $_GET['action'];\n wp_redirect( 'example.com/custompostype/post-title/' . $action, $status = 301 );\n exit;\n}\n</code></pre>\n"
},
{
"answer_id": 288523,
"author": "brianjohnhanna",
"author_id": 65403,
"author_profile": "https://wordpress.stackexchange.com/users/65403",
"pm_score": 0,
"selected": false,
"text": "<p>I'm pretty sure if you need to use the <code>action</code> parameter you will have some mixed results, as this is one WordPress uses under the hood for a lot of things. If you have flexibility over the name of the parameter, this is indeed possible. I am unable to test this at the moment but this should get you headed in the right direction.</p>\n\n<pre><code>function wpse_cpt_rewrite_rule() {\n add_rewrite_rule('^customposttype/([^/]*)/([^/]*)/?','index.php?pagename=$matches[1]&action=$matches[2]','top');\n}\nadd_action('init', 'wpse_cpt_rewrite_rule', 10, 0);\n</code></pre>\n\n<p>It should be noted that if you don't use the <code>action</code> parameter, you'll need to register your custom param like so as well.</p>\n\n<pre><code>function wpse_add_custom_tag() {\n add_rewrite_tag('%my_custom_action%', '([^&]+)');\n}\nadd_action('init', 'wpse_add_custom_tag', 10, 0);\n</code></pre>\n"
},
{
"answer_id": 288585,
"author": "Amenadiel17",
"author_id": 133205,
"author_profile": "https://wordpress.stackexchange.com/users/133205",
"pm_score": 1,
"selected": false,
"text": "<p>I just realized i used different kind of rewriting which didn't require @Jacob's codes (using add_rewrite_endpoint)</p>\n\n<pre><code>add_action('init', 'wpse42279_add_endpoints');\nfunction wpse42279_add_endpoints()\n{\n add_rewrite_endpoint('play', EP_PERMALINK);\n}\n</code></pre>\n\n<p>And then i used this conditionals on the single page:</p>\n\n<pre><code>global $post;\n$pid = $post->ID;\n$var = get_query_var( 'play' ); \nif( !empty($var) and $var == $pid) :\n// do stuff\nendif;\n</code></pre>\n\n<p><strong>Now here's the working pretty link:</strong></p>\n\n<pre><code>example.com/custompostype/post-title/play/123/\n</code></pre>\n\n<p><strong>Instead of:</strong>\nexample.com/custompostype/post-title/?play=123</p>\n\n<p>However the problem now is that the old url still exist (example.com/custompostype/post-title/?play=123) and still accessible/visible. Is it possible to make it work like how this code works: </p>\n\n<pre><code>example.com/?custompostype=321\n</code></pre>\n\n<p>(It redirects to the pretty link: example.com/custompostype/post-title/)</p>\n"
}
]
| 2017/12/13 | [
"https://wordpress.stackexchange.com/questions/288540",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/30753/"
]
| I am creating a membership site where I am trying to login a particular user from a link sent to their email address.
I have a custom post typed called "Members", where I have stored a unique key with the name "user\_key". After a particular process, the email is sent to that user with an auto login link.
An example link looks like the following
<http://example.com/process/?key=DcP2K7cmBUrLVRjizs78RAuuoMGRFc6F6TMDm6E6>
Process is the page which handles the login part. Here is the code used in that page.
```
get_header();
$key = $_GET['key'];
$args = array(
'post_type' => 'member',
'meta_value' => $key
);
$properties = new WP_Query($args);
if($properties->have_posts()) :
while($properties->have_posts()) : $properties->the_post();
$author = $post->post_author;
$user = get_user_by('ID', $author);
$user_id = $user->ID;
echo $user_id;
wp_set_current_user($user_id, $loginusername);
wp_set_auth_cookie($user_id);
do_action('wp_login', $loginusername);
wp_redirect( home_url() );
endwhile;
endif;
wp_reset_query();
get_footer();
```
When I go to that particular link, I get the following error.
"Warning: Cannot modify header information - headers already sent"
From what I understand, I think it's the "wp\_set\_auth\_cookie" part which is done after the headers are loaded, which is creating that problem.
Anyone has any ideas how to fix it? | I just realized i used different kind of rewriting which didn't require @Jacob's codes (using add\_rewrite\_endpoint)
```
add_action('init', 'wpse42279_add_endpoints');
function wpse42279_add_endpoints()
{
add_rewrite_endpoint('play', EP_PERMALINK);
}
```
And then i used this conditionals on the single page:
```
global $post;
$pid = $post->ID;
$var = get_query_var( 'play' );
if( !empty($var) and $var == $pid) :
// do stuff
endif;
```
**Now here's the working pretty link:**
```
example.com/custompostype/post-title/play/123/
```
**Instead of:**
example.com/custompostype/post-title/?play=123
However the problem now is that the old url still exist (example.com/custompostype/post-title/?play=123) and still accessible/visible. Is it possible to make it work like how this code works:
```
example.com/?custompostype=321
```
(It redirects to the pretty link: example.com/custompostype/post-title/) |
288,564 | <p>I need to include jquery in a single page template of my theme. But it looks like it doesn't want to.</p>
<p>I tried calling it with wp_enqueue_scripts() but i does nothing.
Here is what is in functions.php</p>
<pre><code>add_action( 'wp_enqueue_scripts', 'custom_theme_load_scripts' );
function custom_theme_load_scripts()
{
wp_enqueue_script( 'jquery' );
}
</code></pre>
<p>And what I'm trying to do in page-template.php</p>
<pre><code><?php custom_theme_load_scripts(); ?>
<script type="text/javascript">
//stuff using jquery here
</script>
</code></pre>
<p>Even calling it before the header doesn't work.</p>
<p>I don't want to load an external jquery file since wordpress already have one, but I'm banging my head against the wall as I have no idea why it doesn't work.</p>
<p>Any ideas ?</p>
| [
{
"answer_id": 288572,
"author": "dipak_pusti",
"author_id": 44528,
"author_profile": "https://wordpress.stackexchange.com/users/44528",
"pm_score": 0,
"selected": false,
"text": "<p>What you are trying to do in <code>page-template.php</code> is totally wrong. Try to run conditional query while enqueing jquery. Here is the code that may help you.</p>\n<pre><code>add_action( 'wp_enqueue_scripts', 'custom_theme_load_scripts' );\nfunction custom_theme_load_scripts() {\n \n // If you want to disable from all other pages\n wp_dequeue_script('jquery');\n\n // Add to your page template\n if( is_page_template('YOUR_TEMPLATE_NAME') ) {\n \n // Now enqueue jQuery again\n wp_enqueue_script( 'jquery' );\n }\n}\n</code></pre>\n<p>If it is not page template and some other conditons like single page or single post or anything you want, WordPress has a conditional query for every condition. Checkout the following page,</p>\n<p><a href=\"https://codex.wordpress.org/Conditional_Tags\" rel=\"nofollow noreferrer\">https://codex.wordpress.org/Conditional_Tags</a></p>\n<p>Hope this one helps :)</p>\n"
},
{
"answer_id": 288575,
"author": "Dylan",
"author_id": 41351,
"author_profile": "https://wordpress.stackexchange.com/users/41351",
"pm_score": 1,
"selected": false,
"text": "<p>It sounds like your template is missing a call to <code>wp_head()</code> which will output your enqueued scripts and styles. You'd normally place <code>wp_head()</code> in your <code>header.php</code> template and include this in your page template. </p>\n\n<p>To conditionally enqueue jQuery based on the page template being used you could use the following code:</p>\n\n<pre><code>add_action( 'wp_enqueue_scripts', 'custom_theme_load_scripts' );\nfunction custom_theme_load_scripts() { \n if ( is_page_template( 'page-template.php' ) ) {\n wp_enqueue_script( 'jquery' );\n } \n}\n</code></pre>\n\n<p>Keep in mind that plugins may require jQuery and therefore enqueue it on other pages/templates.</p>\n"
},
{
"answer_id": 288609,
"author": "Gawet",
"author_id": 132140,
"author_profile": "https://wordpress.stackexchange.com/users/132140",
"pm_score": 1,
"selected": true,
"text": "<p>Okay, this is awkward but I resolved my own issue.\njQuery was indeed charging but... I was using <code>$this</code>.</p>\n\n<p>And as someone already said on another thread:</p>\n\n<blockquote>\n <p>By default when you enqueue jQuery in Wordpress you must use jQuery, and $ is not used (this is for compatibility with other libraries).</p>\n</blockquote>\n\n<p>So, you must use <code>jquery</code> as a selector instead of <code>$</code>.</p>\n\n<p>Hope it can help someone else !</p>\n\n<p>Thanks a everyone trying to help !</p>\n"
}
]
| 2017/12/14 | [
"https://wordpress.stackexchange.com/questions/288564",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/132140/"
]
| I need to include jquery in a single page template of my theme. But it looks like it doesn't want to.
I tried calling it with wp\_enqueue\_scripts() but i does nothing.
Here is what is in functions.php
```
add_action( 'wp_enqueue_scripts', 'custom_theme_load_scripts' );
function custom_theme_load_scripts()
{
wp_enqueue_script( 'jquery' );
}
```
And what I'm trying to do in page-template.php
```
<?php custom_theme_load_scripts(); ?>
<script type="text/javascript">
//stuff using jquery here
</script>
```
Even calling it before the header doesn't work.
I don't want to load an external jquery file since wordpress already have one, but I'm banging my head against the wall as I have no idea why it doesn't work.
Any ideas ? | Okay, this is awkward but I resolved my own issue.
jQuery was indeed charging but... I was using `$this`.
And as someone already said on another thread:
>
> By default when you enqueue jQuery in Wordpress you must use jQuery, and $ is not used (this is for compatibility with other libraries).
>
>
>
So, you must use `jquery` as a selector instead of `$`.
Hope it can help someone else !
Thanks a everyone trying to help ! |
288,581 | <p>Issue URL - <a href="http://www.creativescripters.com/clients/testwp/uncategorized/image-resized/" rel="nofollow noreferrer">http://www.creativescripters.com/clients/testwp/uncategorized/image-resized/</a></p>
<p>I am using wordpress (self hosted) latest version, The problem is I am looking to get a thumbnail from the resized/scaled image, and when I do that wordpress returns the test-150x150.jpg i.e. Thumbnail from the original image and not the resized image which should have been test-e1513229707262-150x150.jpg</p>
<p>Step to reproduce the issue </p>
<ol>
<li>Upload an image , Scale it (click edit on uploaded image and change width and click scale). Wordpress will rename the image and add an Suffix Id to the name so you can confirm the image have been scaled. for eg if you uploaded test.jpg after scaling image name will become test-randomstring.jpg</li>
</ol>
<p><a href="https://i.stack.imgur.com/TTIaG.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/TTIaG.png" alt="enter image description here"></a></p>
<ol start="2">
<li><p>When I call get_the_post_thumbnail($post, 'full') I get the correct image The resized one i.e. test-randomstring.jpg
<a href="https://i.stack.imgur.com/T3vPE.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/T3vPE.png" alt="enter image description here"></a></p></li>
<li><p>When I try to get a different size of the scaled image for eg I need thumbnail generated from the image size and I call function get_the_post_thumbnail($post, 'thumbnail') wordpress return the THUMBNAIL from actual image (the one I uploaded initially test.jpg and not the resized one test-randomstring.jpg)</p></li>
</ol>
<p>Screenshot - <a href="https://i.imgur.com/sQKoZcF.png" rel="nofollow noreferrer">https://i.imgur.com/sQKoZcF.png</a></p>
| [
{
"answer_id": 288584,
"author": "Tarang koradiya",
"author_id": 128666,
"author_profile": "https://wordpress.stackexchange.com/users/128666",
"pm_score": 2,
"selected": false,
"text": "<p>Used img tag and display image</p>\n\n<pre><code><img src=\"<?= $img_url=get_the_post_thumbnail_url($post->ID,'full'); ?>\" alt=\"image\" />\n</code></pre>\n"
},
{
"answer_id": 289084,
"author": "BlueSuiter",
"author_id": 92665,
"author_profile": "https://wordpress.stackexchange.com/users/92665",
"pm_score": 2,
"selected": false,
"text": "<p>Use <code>post-thumbnail</code> instead of <code>thumbnail</code>. Your final code will be <code>get_the_post_thumbnail($post, 'post-thumbnail');</code>.\nPlease refer to this <a href=\"https://developer.wordpress.org/reference/functions/get_the_post_thumbnail/\" rel=\"nofollow noreferrer\">link</a></p>\n"
},
{
"answer_id": 289261,
"author": "shramee",
"author_id": 92887,
"author_profile": "https://wordpress.stackexchange.com/users/92887",
"pm_score": 2,
"selected": false,
"text": "<p>You may want to try adding <code>IMAGE_EDIT_OVERWRITE</code> constant in your wp-config file to force WP to purge old images and use new ones.</p>\n\n<p>Function <code>wp_save_image()</code> is what processes the image and it is called by <code>wp_ajax_image_editor()</code> which is the AJAX handler for image editor AJAX endpoints.</p>\n\n<p>You can read more about how it works in file <code>/wp-includes/image-edit.php</code> or browse it's source code online @ <a href=\"https://developer.wordpress.org/reference/functions/wp_save_image/\" rel=\"nofollow noreferrer\">https://developer.wordpress.org/reference/functions/wp_save_image/</a></p>\n\n<p>However, I'm still not sure if this is really an issue,</p>\n\n<ol>\n<li>Original image is say 1024x707</li>\n<li>WP converts it to thumbnail size along with other sizes.</li>\n<li>You get a thumbnail from that image that is 150x150.</li>\n<li>You resize it to say 400x276.</li>\n<li>Now thumbnail for that image would actually be identical to the thumb of first image.</li>\n</ol>\n\n<p>So result is pretty much the same either way :)</p>\n"
},
{
"answer_id": 289358,
"author": "Ted",
"author_id": 44012,
"author_profile": "https://wordpress.stackexchange.com/users/44012",
"pm_score": 2,
"selected": false,
"text": "<p>You have to add the appropriate image size in your theme's functions.php file</p>\n\n<p><code>add_image_size('my_post_thumbnial', 400, 99999, false);</code></p>\n\n<p>400 is width, 99999 is height, false is do not crop. This must be \"after\" add_theme_support(post-thumbnails); so find that and place the above code after it.</p>\n\n<p>You don't have to regenerate all your images... just re-upload the ones you need. Optionally, the Regenerate Thumbnails plugin (<a href=\"https://wordpress.org/plugins/regenerate-thumbnails/\" rel=\"nofollow noreferrer\">https://wordpress.org/plugins/regenerate-thumbnails/</a>) adds a link to each image in your media library to regenerate that particular image.</p>\n\n<p>Then call your thumbnail with <code>the_post_thumbnail('my_post_thumbnial');</code></p>\n"
},
{
"answer_id": 289361,
"author": "CK MacLeod",
"author_id": 35923,
"author_profile": "https://wordpress.stackexchange.com/users/35923",
"pm_score": 2,
"selected": false,
"text": "<h2>ALWAYS REGENERATE SOURCE SET ON IMAGE EDIT</h2>\n\n<p>(New material, especially the custom function, follows conversation in comment thread.)</p>\n\n<p>The following function automatically regenerates a full source set after an image edit action. </p>\n\n<pre><code>/**\n * ALWAYS REGENERATE FULL SOURCE SET AFTER EDITING IMAGE\n * answering StackExchange WordPress Development Question\n * see: https://wordpress.stackexchange.com/questions/288581/image-scaling-using-get-the-post-thumbnail-issue-in-wordpress/\n * exploits code already worked out in Regenerate Thumbnails Plugin\n */\nadd_action( 'edit_attachment', 'wpse_always_regenerate', 99);\n\nfunction wpse_always_regenerate( $postID ) {\n\n $new_url = get_attached_file( $postID );\n\n $metadata = wp_generate_attachment_metadata( $postID, $new_url );\n\n wp_update_attachment_metadata( $postID, $metadata );\n\n}\n</code></pre>\n\n<p>You would add this to your theme functions.php file if that's what you wanted to occur - if you were happy with index number generated and added to the original image, and were happy with the complete source set being governed by the edited (re-scaled) image. It happens to leave the original upload and its set in the folder. (Adding an optionalized \"cleaner\" operation is something I haven't gotten into, but there are plugins that will clean up unattached/unused images from a folder already - one could be applied on a semi-regular basis.)</p>\n\n<p>I have not tested it for possible unwanted additional interactions. In most installations, it wouldn't hurt, might even help, though I can imagine some circumstances in which you might NOT want all image edit actions to \"regenerate thumbnails\" (which probably ought to be named \"regenerate source set\"). For those installations, you'd obviously want something more refined.</p>\n\n<hr>\n\n<h2>FULL DISCUSSION</h2>\n\n<p>Though a little more clarity on the initial question and how exactly to reproduce it would be helpful, I believe the answer is something along these lines: </p>\n\n<p>When you upload an image, WordPress will upload the full version of the image, along with the normal set of thumbnails. If you scale the image, it will also create one specific variation, with the random number addition. So, on one installation, when I upload an image as post featured image and proceed to re-scale it, I get the following in my Uploads folder:</p>\n\n<p><a href=\"https://i.stack.imgur.com/aauQV.jpg\" rel=\"nofollow noreferrer\"><img src=\"https://i.stack.imgur.com/aauQV.jpg\" alt=\"![enter image description here\"></a></p>\n\n<p>If I ask for <code>get_the_post_thumbnail( $postID, $type )</code>, I get:</p>\n\n<p><strong>full</strong> : </p>\n\n<pre><code><img \n width=\"500\" \n height=\"651\" \n src=\"http://ckmswp.com/wp-content/uploads/2017/12/pingdom_topline_before-e1514050718361.jpg\" \n class=\"attachment-full size-full wp-post-image\" \n alt=\"\" \n sizes=\"100vw\" \n/>\n</code></pre>\n\n<p><strong>post-thumbnail</strong> :</p>\n\n<pre><code><img \n width=\"500\" \n height=\"651\" \n src=\"http://ckmswp.com/wp-content/uploads/2017/12/pingdom_topline_before-e1514050718361.jpg\" \n class=\"attachment-post-thumbnail size-post-thumbnail wp-post-image\" \n alt=\"\" \n sizes=\"100vw\" \n/>\n</code></pre>\n\n<p><strong>thumbnail</strong> : </p>\n\n<pre><code><img \n width=\"150\" \n height=\"150\" \n src=\"http://ckmswp.com/wp-content/uploads/2017/12/pingdom_topline_before-150x150.jpg\" \n class=\"attachment-thumbnail size-thumbnail wp-post-image\" alt=\"\" \n srcset=\"https://ckmswp.com/wp-content/uploads/2017/12/pingdom_topline_before-150x150.jpg 150w, \n https://ckmswp.com/wp-content/uploads/2017/12/pingdom_topline_before-100x100.jpg 100w\" \n sizes=\"100vw\" \n/>\n</code></pre>\n\n<p>So, in scaling the image on upload, I create a new \"full\" version of the image - with the \"random\" code added to the original filename, and, since I was uploading it as a Featured Image, it is now also slotted as the 'post-thumbnail' image.</p>\n\n<p>This can also be verified using wp_get_attachment_image_src(), which, for \"full\" on the above, returns:</p>\n\n<pre><code>(\n [0] => http://ckmswp.com/wp-content/uploads/2017/12/pingdom_topline_before-e1514050718361.jpg\n [1] => 500\n [2] => 651\n [3] => \n)\n</code></pre>\n\n<p>So, in short, if you call for one of the named images in the usual image set, you'll get the ones created before you scaled the image. If - assuming you scaled the image when uploading it as a featured image - you call for either the full image or the (in this installation) <code>post-thumbnail</code> image, you'll also get the new scaled image. </p>\n\n<p>To get the original full image, I think you might have to access the attachment object, which looks like this:</p>\n\n<pre><code>[64755] => WP_Post Object\n (\n [ID] => 64755\n [post_author] => 1\n [post_date] => 2017-12-23 17:38:24\n [post_date_gmt] => 2017-12-23 17:38:24\n [post_content] => \n [post_title] => pingdom_topline_before\n [post_excerpt] => \n [post_status] => inherit\n [comment_status] => open\n [ping_status] => closed\n [post_password] => \n [post_name] => pingdom_topline_before\n [to_ping] => \n [pinged] => \n [post_modified] => 2017-12-23 17:38:24\n [post_modified_gmt] => 2017-12-23 17:38:24\n [post_content_filtered] => \n [post_parent] => 64752\n [guid] => **http://ckmswp.com/wp-content/uploads/2017/12/pingdom_topline_before.jpg**\n [menu_order] => 0\n [post_type] => attachment\n [post_mime_type] => image/jpeg\n [comment_count] => 0\n [filter] => raw\n )\n\n)\n</code></pre>\n\n<p><strong>If you wanted to get a 150x150 (or whatever is set for you installation for thumbnail) version of the scaled image, you'd have to either:</strong></p>\n\n<p><strong>1) upload the scaled image separately, and let WordPress generate the test-image-random-150x150.jpg for you. or</strong></p>\n\n<p><strong>2) Achieve a similar effect by \"regenerating thumbnails.\"</strong></p>\n\n<p>After such a regeneration action, my uploads folder shows the following:</p>\n\n<p><a href=\"https://i.stack.imgur.com/TsrDU.jpg\" rel=\"nofollow noreferrer\"><img src=\"https://i.stack.imgur.com/TsrDU.jpg\" alt=\"enter image description here\"></a></p>\n\n<p>Note that the original image set is left unaltered in the folder. </p>\n\n<p>Creating such a re-generated image set would be the preferable method especially if you intend to use the scaled image for other purposes, since re-uploading it and letting it generate the full source set of images appropriate to your installation will help with responsiveness and consistency. </p>\n\n<p>To achieve those purposes, you'll need a custom function (such as the one provided at the outset of this answer), and a more complex, optionalized implementation might be worth considering, even though I'm not convinced it would be used very often. (When I want to scale an image to particular dimensions, I almost always do it separately from WP, and give it a name that makes sense to me, but I can't speak for others.)</p>\n\n<p>If you wish to get a complete source set of images (relative to the new scaled image), and don't wish to re-upload the new scaled image, or rely on the function to do it for you whenever you edit an image in the Library, you can use Regenerate Thumbnails or similar plugin. Finally, you can also crop (or false crop) the image to produce the set of thumbnails. </p>\n\n<p>This last one is easy to execute: In addition to re-scaling the image, in \"edit image\" you can use the cropping tool to produce a virtual near-copy of the original - and WordPress will produce the full source set when you save the image. I say near-copy because in tests the editor will not let you completely save a \"copy\" actually identical to the original, but at this point I have no choice but to examine the code in detail if I want to understand, and that's something I'll leave to another day and maybe write up somewhere else - unless someone else comes along with the full briefing first. </p>\n\n<p>So, in sum,</p>\n\n<p><strong>1. When you first upload an image, WordPress creates a set of thumbnails based on the uploaded file.</strong></p>\n\n<p><strong>2. If you simply re-scale the image, it will produce a single unique scaled image, with a generated filename based on the original name, with the addition of a \"random\" element (actually a heterogeneous index number)</strong> </p>\n\n<p><strong>3. If you re-upload the new scaled image or if you regenerate thumbnails - using a custom function, a plugin, or an editing trick - you can produce a new set of images based on the scaled image, using the generated filename.</strong> </p>\n"
}
]
| 2017/12/14 | [
"https://wordpress.stackexchange.com/questions/288581",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/10639/"
]
| Issue URL - <http://www.creativescripters.com/clients/testwp/uncategorized/image-resized/>
I am using wordpress (self hosted) latest version, The problem is I am looking to get a thumbnail from the resized/scaled image, and when I do that wordpress returns the test-150x150.jpg i.e. Thumbnail from the original image and not the resized image which should have been test-e1513229707262-150x150.jpg
Step to reproduce the issue
1. Upload an image , Scale it (click edit on uploaded image and change width and click scale). Wordpress will rename the image and add an Suffix Id to the name so you can confirm the image have been scaled. for eg if you uploaded test.jpg after scaling image name will become test-randomstring.jpg
[](https://i.stack.imgur.com/TTIaG.png)
2. When I call get\_the\_post\_thumbnail($post, 'full') I get the correct image The resized one i.e. test-randomstring.jpg
[](https://i.stack.imgur.com/T3vPE.png)
3. When I try to get a different size of the scaled image for eg I need thumbnail generated from the image size and I call function get\_the\_post\_thumbnail($post, 'thumbnail') wordpress return the THUMBNAIL from actual image (the one I uploaded initially test.jpg and not the resized one test-randomstring.jpg)
Screenshot - <https://i.imgur.com/sQKoZcF.png> | Used img tag and display image
```
<img src="<?= $img_url=get_the_post_thumbnail_url($post->ID,'full'); ?>" alt="image" />
``` |
288,595 | <p>I'm trying to create some custom REST API endpoints which get products with some special conditions, for example, one endpoint for featured products.
I tried to use the <code>wc_get_products</code> function like this:</p>
<pre><code>add_action('rest_api_init', 'my_custom_featured_product_endpoint');
function my_custom_featured_product_endpoint() {
register_rest_route('custom-endpoints/v1', '/products/featured', array(
'methods' => 'GET',
'callback' => 'my_custom_featured_product_callback',
));
}
function my_custom_featured_product_callback() {
$meta_query = WC()->query->get_meta_query();
$tax_query = WC()->query->get_tax_query();
$tax_query[] = array(
'taxonomy' => 'product_visibility',
'field' => 'name',
'terms' => 'featured',
'operator' => 'IN',
);
$args = array(
'tax_query' => $tax_query,
'meta_query' => $meta_query,
);
$result = wc_get_products($args);
return rest_ensure_response($result);
}
</code></pre>
<p>The result is just some empty arrays. I can get those products with old fashion <code>get_posts</code> to replace <code>wc_get_products</code> but the output format doesn't have some properties like 'price', 'images' ...</p>
<p>So are there any alternatives for <code>wc_get_products</code> to use for custom REST API endpoints or are there any ways to make it work?</p>
<p>P/S: I tested the query by change the callback function like so:</p>
<pre><code>function my_custom_featured_product_callback() {
$result = wc_get_product(99);//Yes there is a product with ID 99
return rest_ensure_response($result);
}
</code></pre>
<p>The result stays the same, just an empty array. So I think the issue must lie with the <code>wc_get_products</code> and <code>wc_get_product</code> functions. Maybe the <code>rest_api_init</code> is not the proper hook for those functions?</p>
| [
{
"answer_id": 307143,
"author": "Brauperle",
"author_id": 145985,
"author_profile": "https://wordpress.stackexchange.com/users/145985",
"pm_score": 0,
"selected": false,
"text": "<p>I faced a similar behavior where <code>$wc_get_product</code> always returned empty objects from a custom REST endpoint when I was checking the response with a console.log on the front end side.</p>\n\n<p>It was because I was returning the PHP Object directly in the response, I solved the issue by converting the Product Object to an array with the help of the thread bellow :</p>\n\n<p><a href=\"https://stackoverflow.com/questions/4345554/convert-php-object-to-associative-array\">convert-php-object-to-associative-array</a></p>\n\n<p>After that it worked as expected, hopefully it'll be the same for you!</p>\n"
},
{
"answer_id": 320075,
"author": "Arash Rabiee",
"author_id": 129717,
"author_profile": "https://wordpress.stackexchange.com/users/129717",
"pm_score": 2,
"selected": false,
"text": "<p>you missed something, when you get a product using wc_get_product it returns to you an abstract object, so if you need to get product do this</p>\n\n<pre><code>$product = wc_get_product($product_id);\nreturn $product->get_data();\n</code></pre>\n\n<p>also you can use all the other functionalities too, such as:</p>\n\n<pre><code>$product->get_status();\n$product->get_gallery_image_ids();\n...\n</code></pre>\n"
},
{
"answer_id": 360690,
"author": "Vala Khosravi",
"author_id": 184264,
"author_profile": "https://wordpress.stackexchange.com/users/184264",
"pm_score": 0,
"selected": false,
"text": "<p>Add <code>(array)</code> cast before <code>wc_get_products($args)</code> like this:</p>\n\n<pre><code>$result = (array) wc_get_products($args);\n</code></pre>\n\n<p>If an object is converted to an array, the result is an array whose elements are the object's properties. The keys are the member variable names, with a few notable exceptions: integer properties are unaccessible; private variables have the class name prepended to the variable name; protected variables have a '*' prepended to the variable name. These prepended values have null bytes on either side. and you can access to product data by <code>*data</code> property.</p>\n"
}
]
| 2017/12/14 | [
"https://wordpress.stackexchange.com/questions/288595",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/133259/"
]
| I'm trying to create some custom REST API endpoints which get products with some special conditions, for example, one endpoint for featured products.
I tried to use the `wc_get_products` function like this:
```
add_action('rest_api_init', 'my_custom_featured_product_endpoint');
function my_custom_featured_product_endpoint() {
register_rest_route('custom-endpoints/v1', '/products/featured', array(
'methods' => 'GET',
'callback' => 'my_custom_featured_product_callback',
));
}
function my_custom_featured_product_callback() {
$meta_query = WC()->query->get_meta_query();
$tax_query = WC()->query->get_tax_query();
$tax_query[] = array(
'taxonomy' => 'product_visibility',
'field' => 'name',
'terms' => 'featured',
'operator' => 'IN',
);
$args = array(
'tax_query' => $tax_query,
'meta_query' => $meta_query,
);
$result = wc_get_products($args);
return rest_ensure_response($result);
}
```
The result is just some empty arrays. I can get those products with old fashion `get_posts` to replace `wc_get_products` but the output format doesn't have some properties like 'price', 'images' ...
So are there any alternatives for `wc_get_products` to use for custom REST API endpoints or are there any ways to make it work?
P/S: I tested the query by change the callback function like so:
```
function my_custom_featured_product_callback() {
$result = wc_get_product(99);//Yes there is a product with ID 99
return rest_ensure_response($result);
}
```
The result stays the same, just an empty array. So I think the issue must lie with the `wc_get_products` and `wc_get_product` functions. Maybe the `rest_api_init` is not the proper hook for those functions? | you missed something, when you get a product using wc\_get\_product it returns to you an abstract object, so if you need to get product do this
```
$product = wc_get_product($product_id);
return $product->get_data();
```
also you can use all the other functionalities too, such as:
```
$product->get_status();
$product->get_gallery_image_ids();
...
``` |
288,650 | <p>I have a front-end form posting to admin_post. Here, I do some validation. If there are errors, I want to show an error message for the relevant fields.</p>
<p>However, I don't know how to redirect back to the submission page and retain the field values.</p>
<p>Currently I'm using the below:.</p>
<pre><code>add_action( 'admin_post_form', 'form_post' );
function form_post() {
$validate = // Validation functions go here
if ($validate == 'error') {
$url = wp_get_referer();
$url = add_query_arg( 'error', 'email', $url );
wp_redirect( $url );
die();
}
}
</code></pre>
<p>But this (naturally) doesn't retain the filled form field values, so the user has to start all over again.</p>
<p>If I were posting to the same page as the form this would be simple - just set the value as <code><input value="<?php echo $_POST['email']; ?>"></code> but I'm not sure how to achieve the same effect using admin-post.</p>
<p>Can you help?</p>
| [
{
"answer_id": 295462,
"author": "Kevin Robinson",
"author_id": 133315,
"author_profile": "https://wordpress.stackexchange.com/users/133315",
"pm_score": 0,
"selected": false,
"text": "<p>I solved this using the $_SESSION variable to pass data to the following page.</p>\n\n<pre><code> if ($validate == 'error') {\n $_SESSION['formstatus'] = 'error';\n $_SESSION['formdata'] = $_POST;\n $url = wp_get_referer();\n wp_redirect( $url );\n die();\n }\n</code></pre>\n\n<p>And</p>\n\n<pre><code><input name=\"email\" value=\"<?php echo $_SESSION['formdata']['email']\">\n</code></pre>\n\n<p>Finally, clear the data at the bottom of the page, after we've used it...</p>\n\n<pre><code>$_SESSION['formstatus'] = $_SESSION['formdata'] = null;\n</code></pre>\n"
},
{
"answer_id": 295468,
"author": "Mark Kaplun",
"author_id": 23970,
"author_profile": "https://wordpress.stackexchange.com/users/23970",
"pm_score": 0,
"selected": false,
"text": "<p>You should just pass all the arguments. This obviously not a great solution when trying to pass them on the URL, so use of cookies might be a much better solution.</p>\n\n<p>But frankly, on a modern web site you should just use AJAX, report and handle the errors on browser side and also redirect from it.</p>\n"
},
{
"answer_id": 328013,
"author": "Solomon Closson",
"author_id": 54603,
"author_profile": "https://wordpress.stackexchange.com/users/54603",
"pm_score": 1,
"selected": false,
"text": "<p>You can use <code>set_transient</code> with the <code>user_id</code> if you are relying on users being logged in, otherwise, cookie would probably be better. For logged in users, you can have the <code>user_id</code> get set within the name of the transient. An example here:</p>\n\n<pre><code>function form_post() {\n $user_info = wp_get_current_user();\n $user_id = $user_info->exists() && !empty($user_info->ID) ? $user_info->ID : 0;\n $url = wp_get_referer();\n\n // Validate the form fields and populate this array when errors occur\n $validation_errors = array(); // I like to use the id of the elements as keys and the error string as the values of the array, so i can add error class to the elements if needed easily...\n\n // Now to save the transient...\n if (!empty($validation_errors)) {\n set_transient('validation_errors_' . $user_id, $my_errors);\n wp_redirect($url);\n die();\n }\n}\n</code></pre>\n\n<p>Now before you output your form element on your page, you just need to check the transient for that user, if exists, output the errors, than delete the transient right after that...</p>\n\n<p>For example:</p>\n\n<pre><code><?php \n$user_info = wp_get_current_user();\n\n$user_id = $user_info->exists() && !empty($user_info->ID) ? $user_info->ID : 0;\n$validation_errors = get_transient('validation_errors_' . $user_id);\n\nif ($validation_errors !== FALSE) {\n echo '<div class=\"errors\">Please fix the following Validation Errors:<ul><li>' . implode('</li><li>', $validation_errors) . '</li></ul></div>';\n delete_transient('validation_errors_' . $user_id);\n} ?>\n\n<form ...>\n\n</form>\n</code></pre>\n"
}
]
| 2017/12/14 | [
"https://wordpress.stackexchange.com/questions/288650",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/133315/"
]
| I have a front-end form posting to admin\_post. Here, I do some validation. If there are errors, I want to show an error message for the relevant fields.
However, I don't know how to redirect back to the submission page and retain the field values.
Currently I'm using the below:.
```
add_action( 'admin_post_form', 'form_post' );
function form_post() {
$validate = // Validation functions go here
if ($validate == 'error') {
$url = wp_get_referer();
$url = add_query_arg( 'error', 'email', $url );
wp_redirect( $url );
die();
}
}
```
But this (naturally) doesn't retain the filled form field values, so the user has to start all over again.
If I were posting to the same page as the form this would be simple - just set the value as `<input value="<?php echo $_POST['email']; ?>">` but I'm not sure how to achieve the same effect using admin-post.
Can you help? | You can use `set_transient` with the `user_id` if you are relying on users being logged in, otherwise, cookie would probably be better. For logged in users, you can have the `user_id` get set within the name of the transient. An example here:
```
function form_post() {
$user_info = wp_get_current_user();
$user_id = $user_info->exists() && !empty($user_info->ID) ? $user_info->ID : 0;
$url = wp_get_referer();
// Validate the form fields and populate this array when errors occur
$validation_errors = array(); // I like to use the id of the elements as keys and the error string as the values of the array, so i can add error class to the elements if needed easily...
// Now to save the transient...
if (!empty($validation_errors)) {
set_transient('validation_errors_' . $user_id, $my_errors);
wp_redirect($url);
die();
}
}
```
Now before you output your form element on your page, you just need to check the transient for that user, if exists, output the errors, than delete the transient right after that...
For example:
```
<?php
$user_info = wp_get_current_user();
$user_id = $user_info->exists() && !empty($user_info->ID) ? $user_info->ID : 0;
$validation_errors = get_transient('validation_errors_' . $user_id);
if ($validation_errors !== FALSE) {
echo '<div class="errors">Please fix the following Validation Errors:<ul><li>' . implode('</li><li>', $validation_errors) . '</li></ul></div>';
delete_transient('validation_errors_' . $user_id);
} ?>
<form ...>
</form>
``` |
288,655 | <p>On my search.php page, I have a "Sort By" dropdown that almost works exactly how I want it to --</p>
<pre><code><select class="dropdown-class" name="sort-posts" id="sortbox" onchange="document.location.href=location.href+this.options[this.selectedIndex].value;">
<option disabled>Sort by</option>
<option value="&orderby=date&order=dsc">Newest</option>
<option value="&orderby=date&order=asc">Oldest</option>
</select>
<script type="text/javascript">
<?php if (( $_GET['orderby'] == 'date') && ( $_GET['order'] == 'dsc')) { ?>
document.getElementById('sortbox').value='orderby=date&order=dsc';
<?php } elseif (( $_GET['orderby'] == 'date') && ( $_GET['order'] == 'asc')) { ?>
document.getElementById('sortbox').value='orderby=date&order=asc';
<?php } else { ?>
document.getElementById('sortbox').value='orderby=date&order=desc';
<?php } ?>
</script>
</code></pre>
<p>When Im on the search results page, the sort dropdown will sort the current results according to date by grabbing the url and appending to it then reloading the page with the results ---</p>
<pre><code>// Before
mydomain.com/?s=Search&property_city=new-york-city&beds=Any
// After
mydomain.com/?s=Search&property_city=new-york-city&beds=Any&orderby=date&order=dsc
</code></pre>
<p>However, I am now trying to improve the code further by using it to sort based on numeric custom fields (high to low and low to high).</p>
<p>It seems all the info I can find on the subject have much more complicated ways of doing so. Is there anyway of doing this using the code I already started on?</p>
<p><strong>UPDATE</strong></p>
<p>I seem to be getting closer -</p>
<p>On my search.php page I have this before my loop ----</p>
<pre><code><select class="dropdown-class" name="sort-posts" id="sortbox" onchange="document.location.href=location.href+this.options[this.selectedIndex].value;">
<option disabled>Sort by</option>
<option value="&orderby=date&order=dsc">Newest</option>
<option value="&orderby=date&order=asc">Oldest</option>
<option value="&orderby=property_price&order=asc">Most Expensive</option>
<option value="&orderby=property_price&order=dsc">Least Expensive</option>
<option value="&orderby=property_area&order=dsc">Largest</option>
<option value="&orderby=property_area&order=asc">Smallest</option>
</select>
<script type="text/javascript">
<?php if (( $_GET['orderby'] == 'date') && ( $_GET['order'] == 'dsc')) { ?>
document.getElementById('sortbox').value='orderby=date&order=dsc';
<?php } elseif (( $_GET['orderby'] == 'date') && ( $_GET['order'] == 'asc')) { ?>
document.getElementById('sortbox').value='orderby=date&order=asc';
<?php } elseif (( $_GET['orderby'] == 'property_price') && ( $_GET['order'] == 'asc')) { ?>
document.getElementById('sortbox').value='orderby=property_price&order=asc';
<?php } elseif (( $_GET['orderby'] == 'property_price') && ( $_GET['order'] == 'dsc')) { ?>
document.getElementById('sortbox').value='orderby=property_price&order=dsc';
<?php } elseif (( $_GET['orderby'] == 'property_area') && ( $_GET['order'] == 'asc')) { ?>
document.getElementById('sortbox').value='orderby=property_area&order=asc';
<?php } elseif (( $_GET['orderby'] == 'property_area') && ( $_GET['order'] == 'dsc')) { ?>
document.getElementById('sortbox').value='orderby=property_area&order=dsc';
<?php } else { ?>
document.getElementById('sortbox').value='orderby=date&order=desc';
<?php } ?>
</script>
</code></pre>
<p>where it says "orderby=xxx" I just use my names for my custom fields.</p>
| [
{
"answer_id": 289693,
"author": "Nicolai Grossherr",
"author_id": 22534,
"author_profile": "https://wordpress.stackexchange.com/users/22534",
"pm_score": 1,
"selected": false,
"text": "<p><code>orderby</code> should be e.g. <code>meta_value</code> or <code>meta_value_num</code> β various specific <code>meta_type</code>'s are available β to order by meta data. Additionally a <code>meta_key</code> has to be set and present in the query. To be exact and to avoid misunderstandings, <code>meta_key</code> has to be the <code>keyname</code> of the field you're sorting by. Take a closer look at the <a href=\"https://codex.wordpress.org/Class_Reference/WP_Query#Order_.26_Orderby_Parameters\" rel=\"nofollow noreferrer\">Order & Orderby Parameters</a> and <a href=\"https://codex.wordpress.org/Class_Reference/WP_Query#Custom_Field_Parameters\" rel=\"nofollow noreferrer\">Custum Fields Parameters</a> section of the <code>WP_Query</code> documentation for more information.</p>\n"
},
{
"answer_id": 289702,
"author": "730wavy",
"author_id": 24067,
"author_profile": "https://wordpress.stackexchange.com/users/24067",
"pm_score": 2,
"selected": true,
"text": "<p>Ok I got it figured out using @Nicolai suggestion and also a answer from another question (which I seem to have lost the link to).</p>\n\n<p>For starters, I had to make sure my numbers have no commas in it which I had already done by saving my post meta without it.</p>\n\n<p>Then the code I found in another question, I used and placed into my <strong>functions.php</strong> file --</p>\n\n<pre><code>function wpse139657_orderby(){\n if( isset($_GET['orderby']) ){\n $order = $_GET['order'] or 'DESC';\n set_query_var('orderby', 'meta_value_num');\n //set_query_var('meta_type', 'numeric');\n set_query_var('meta_key', $_GET['orderby']);\n set_query_var('order', $order);\n }\n}\n\nadd_filter('pre_get_posts','wpse139657_orderby');\n</code></pre>\n\n<p>Then on my <strong>search.php</strong> page I used the following code for the select dropdown --</p>\n\n<pre><code><select class=\"dropdown-class\" name=\"sort-posts\" id=\"sortbox\" onchange=\"document.location.href=location.href+this.options[this.selectedIndex].value;\">\n<option disabled>Sort by</option>\n<option value=\"&orderby=date&order=dsc\">Newest</option>\n<option value=\"&orderby=date&order=asc\">Oldest</option>\n<option value=\"&orderby=property_price2&order=DESC\">Most Expensive</option>\n<option value=\"&orderby=property_price2&order=ASC\">Least Expensive</option>\n<option value=\"&orderby=area2&order=DESC\">Largest</option>\n<option value=\"&orderby=area2&order=ASC\">Smallest</option>\n</select>\n</code></pre>\n\n<p>This seems to do the trick and works with pagination, only issues I have right now is --</p>\n\n<blockquote>\n <ol>\n <li>Ugly Urls</li>\n <li>When the page is reloaded with the posts sorted, the dropdown select goes back to default ie \"Newest\" when it should still be on the\n option the user chose.</li>\n </ol>\n</blockquote>\n"
},
{
"answer_id": 289716,
"author": "kierzniak",
"author_id": 132363,
"author_profile": "https://wordpress.stackexchange.com/users/132363",
"pm_score": 1,
"selected": false,
"text": "<p>Form will automaticly add your select value to url when you submit form. There is no need to create such a value <code>&orderby=date&order=dsc</code>. If you want to pass multiple information in single select value you can use simpler value and if statement. For newest option I would use <code>newest</code> as value and add make such a if statement.</p>\n\n<pre><code>// Url /?s=test&order=newest\n\n$orderby = '';\n$order = '';\n\n// Get filtered $_GET['order'] parameter\n$value = filter_input( INPUT_GET, 'order', FILTER_SANITIZE_STRING );\n\nif( $value === 'newest' ) {\n $orderby = 'date';\n $order = 'desc';\n}\n\n// Modify query using $orderby and $order parameters\n</code></pre>\n\n<p>Using JavaScript to select option for me is also bad idea. You should check current <code>order</code> parameter and add selected attribute to your option.</p>\n\n<pre><code>// Url /?s=test&order=newest\n\n// Get filtered $_GET['order'] parameter\n$value = filter_input( INPUT_GET, 'order', FILTER_SANITIZE_STRING );\n$selected = ($value === 'newest') ? 'selected': '' ;\n?>\n\n<select name=\"order\">\n <option value=\"newest\" <?php echo esc_attr( $selected ); ?>></option>\n</select>\n</code></pre>\n\n<p>I think you should not bother making nice url. For a small number of parameters it might be tempting to make nice url but when your app is getting bigger adding additional rewrite case and logic to it is purposeless. If you have to convince your boss or client to give up on nice urls show them Amazon on search page. I'm considering them as specialist and they do not use nice urls during search.</p>\n\n<p>Code below is fully working example how to sort post by <code>date</code>, <code>price</code> and <code>size</code>. Execute <code>wpse_288655_display_form</code> function in place where you want to display the sorting form.</p>\n\n<pre><code>/**\n * Display sort form\n */\nfunction wpse_288655_display_form() {\n\n /**\n * Get all params from url which are not part of our sort form\n * and display it in form as hidden inputs.\n */\n $search_param = filter_input( INPUT_GET, 's', FILTER_SANITIZE_STRING );\n\n /**\n * Current order value to select proper field\n */\n $value = filter_input( INPUT_GET, 'order', FILTER_SANITIZE_STRING );\n ?>\n\n <form method=\"get\">\n <?php wpse_288655_display_select('order', 'Sort by:', wpse_288655_get_order_by_options(), $value ); ?>\n\n <?php\n /**\n * Display all params from url which do not apply to our sort form\n */\n ?>\n <input type=\"hidden\" name=\"s\" value=\"<?php esc_attr_e( $search_param ); ?>\">\n\n <button type=\"submit\"><?php esc_html_e('Sort'); ?></button>\n </form>\n <?php\n}\n\n/**\n * Get sort options\n */\nfunction wpse_288655_get_order_by_options(){\n\n return array(\n '' => '',\n 'newest' => __('Newest'),\n 'oldest' => __('Oldest'),\n 'most_expensive' => __('Most Expensive'),\n 'least_expensive' => __('Least Expensive'),\n 'largest' => __('Largest'),\n 'smallest' => __('Smallest'),\n );\n}\n\n/**\n * Display select field\n */\nfunction wpse_288655_display_select( $name, $label, $options, $value = '' ) {\n ?>\n <label><?php esc_html_e( $label ) ?></label>\n <select name=\"<?php esc_attr_e( $name ) ?>\">\n <?php wpse_288655_display_options( $options, $value ); ?>\n </select>\n <?php\n}\n\n/**\n * Display select options\n */\nfunction wpse_288655_display_options( $options, $value ) {\n\n foreach( $options as $option_value => $option_label ):\n $selected = ( $option_value === $value ) ? ' selected' : '';\n ?>\n <option value=\"<?php esc_attr_e( $option_value ) ?>\"<?php esc_attr_e( $selected ) ?>><?php esc_html_e( $option_label ) ?></option>\n <?php\n\n endforeach;\n}\n\n/**\n * Sort posts using pre_get_posts filter\n */\nfunction wpse_288655_order_posts( $query ) {\n\n /**\n * Execute query only when we are on search page and this is main query\n */\n if ( $query->is_search() && $query->is_main_query() ) {\n\n $value = filter_input( INPUT_GET, 'order', FILTER_SANITIZE_STRING );\n $order_by_options = wpse_288655_get_order_by_options();\n\n if( isset( $order_by_options[ $value ] ) && !empty( $value ) ) {\n\n switch( $value ) {\n case 'newest':\n\n $query->set( 'order', 'desc' );\n $query->set( 'orderby', 'date' );\n\n break;\n\n case 'oldest':\n\n $query->set( 'order', 'asc' );\n $query->set( 'orderby', 'date' );\n\n break;\n case 'most_expensive':\n\n $query->set( 'meta_key', 'price' ); // Your custom meta_key\n\n $query->set( 'order', 'desc' );\n $query->set( 'orderby', 'meta_value_num' );\n\n break;\n case 'least_expensive':\n\n $query->set( 'meta_key', 'price' ); // Your custom meta_key\n\n $query->set( 'order', 'asc' );\n $query->set( 'orderby', 'meta_value_num' );\n\n break;\n case 'largest':\n\n $query->set( 'meta_key', 'size' ); // Your custom meta_key\n\n $query->set( 'order', 'desc' );\n $query->set( 'orderby', 'meta_value_num' );\n\n break;\n case 'smallest':\n\n $query->set( 'meta_key', 'size' ); // Your custom meta_key\n\n $query->set( 'order', 'asc' );\n $query->set( 'orderby', 'meta_value_num' );\n\n break;\n default:\n break;\n }\n }\n }\n}\n\nadd_filter('pre_get_posts', 'wpse_288655_order_posts');\n</code></pre>\n"
},
{
"answer_id": 289905,
"author": "Misha Rudrastyh",
"author_id": 85985,
"author_profile": "https://wordpress.stackexchange.com/users/85985",
"pm_score": -1,
"selected": false,
"text": "<p>For the below answers look very uncertain - for example you can not just hook <code>pre_get_posts</code> because it affects every query on the website, even in WordPress admin area.</p>\n\n<p>My first recommendation for you is to refuse of using JavaScript, I'd like to make your dropdown to look like this:</p>\n\n<pre><code><form action=\"\" method=\"GET\"><select name=\"sortposts\">\n <option disabled>Sort by</option>\n <option value=\"date-DESC\">Newest</option>\n <option value=\"date-ASC\">Oldest</option>\n <option value=\"property_price-ASC\">Most Expensive</option>\n <option value=\"property_price-DESC\">Least Expensive</option>\n.....\n</code></pre>\n\n<p>Great, now in the same <code>search.php</code> file you can do this: </p>\n\n<pre><code><?php\n global $wp_query;\n\n // let's create new array with args\n if( !empty( $_GET['sortposts'] ) ) {\n // I recommend to explode it because we're take 2 param values from one $_GET variable\n $sort_args = explode( \"-\", $_GET['sortposts'] );\n // $sort_args[0] is what we sort\n // $sort_args[1] is how we sort - Ascending or Descending\n $new_args['order'] = $sort_args[1];\n if( $sort_args[0] == 'date' ) {\n // date is a default WP_Query value, so we do nothing\n $new_args['orderby'] == 'date';\n } elseif( $sort_args[0] == 'property_price' ) {\n $new_args['orderby'] = 'meta_value_num';\n $new_args['meta_key'] = 'THIS IS A PROPERTY PRICE META KEY';\n }\n }\n\n $args = array_merge( $wp_query->query_vars, $new_args );\n query_posts( $args );\n</code></pre>\n\n<p>Something like that. But you can use pre_get_posts of course if you want. Just add conditions there, so the filter won't fire on non-relevant pages.</p>\n\n<p>If you would like to implement the filtering with AJAX, you can look at this tutorial as well <a href=\"https://rudrastyh.com/wordpress/ajax-load-more-with-filters.html\" rel=\"nofollow noreferrer\">https://rudrastyh.com/wordpress/ajax-load-more-with-filters.html</a></p>\n"
}
]
| 2017/12/14 | [
"https://wordpress.stackexchange.com/questions/288655",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/24067/"
]
| On my search.php page, I have a "Sort By" dropdown that almost works exactly how I want it to --
```
<select class="dropdown-class" name="sort-posts" id="sortbox" onchange="document.location.href=location.href+this.options[this.selectedIndex].value;">
<option disabled>Sort by</option>
<option value="&orderby=date&order=dsc">Newest</option>
<option value="&orderby=date&order=asc">Oldest</option>
</select>
<script type="text/javascript">
<?php if (( $_GET['orderby'] == 'date') && ( $_GET['order'] == 'dsc')) { ?>
document.getElementById('sortbox').value='orderby=date&order=dsc';
<?php } elseif (( $_GET['orderby'] == 'date') && ( $_GET['order'] == 'asc')) { ?>
document.getElementById('sortbox').value='orderby=date&order=asc';
<?php } else { ?>
document.getElementById('sortbox').value='orderby=date&order=desc';
<?php } ?>
</script>
```
When Im on the search results page, the sort dropdown will sort the current results according to date by grabbing the url and appending to it then reloading the page with the results ---
```
// Before
mydomain.com/?s=Search&property_city=new-york-city&beds=Any
// After
mydomain.com/?s=Search&property_city=new-york-city&beds=Any&orderby=date&order=dsc
```
However, I am now trying to improve the code further by using it to sort based on numeric custom fields (high to low and low to high).
It seems all the info I can find on the subject have much more complicated ways of doing so. Is there anyway of doing this using the code I already started on?
**UPDATE**
I seem to be getting closer -
On my search.php page I have this before my loop ----
```
<select class="dropdown-class" name="sort-posts" id="sortbox" onchange="document.location.href=location.href+this.options[this.selectedIndex].value;">
<option disabled>Sort by</option>
<option value="&orderby=date&order=dsc">Newest</option>
<option value="&orderby=date&order=asc">Oldest</option>
<option value="&orderby=property_price&order=asc">Most Expensive</option>
<option value="&orderby=property_price&order=dsc">Least Expensive</option>
<option value="&orderby=property_area&order=dsc">Largest</option>
<option value="&orderby=property_area&order=asc">Smallest</option>
</select>
<script type="text/javascript">
<?php if (( $_GET['orderby'] == 'date') && ( $_GET['order'] == 'dsc')) { ?>
document.getElementById('sortbox').value='orderby=date&order=dsc';
<?php } elseif (( $_GET['orderby'] == 'date') && ( $_GET['order'] == 'asc')) { ?>
document.getElementById('sortbox').value='orderby=date&order=asc';
<?php } elseif (( $_GET['orderby'] == 'property_price') && ( $_GET['order'] == 'asc')) { ?>
document.getElementById('sortbox').value='orderby=property_price&order=asc';
<?php } elseif (( $_GET['orderby'] == 'property_price') && ( $_GET['order'] == 'dsc')) { ?>
document.getElementById('sortbox').value='orderby=property_price&order=dsc';
<?php } elseif (( $_GET['orderby'] == 'property_area') && ( $_GET['order'] == 'asc')) { ?>
document.getElementById('sortbox').value='orderby=property_area&order=asc';
<?php } elseif (( $_GET['orderby'] == 'property_area') && ( $_GET['order'] == 'dsc')) { ?>
document.getElementById('sortbox').value='orderby=property_area&order=dsc';
<?php } else { ?>
document.getElementById('sortbox').value='orderby=date&order=desc';
<?php } ?>
</script>
```
where it says "orderby=xxx" I just use my names for my custom fields. | Ok I got it figured out using @Nicolai suggestion and also a answer from another question (which I seem to have lost the link to).
For starters, I had to make sure my numbers have no commas in it which I had already done by saving my post meta without it.
Then the code I found in another question, I used and placed into my **functions.php** file --
```
function wpse139657_orderby(){
if( isset($_GET['orderby']) ){
$order = $_GET['order'] or 'DESC';
set_query_var('orderby', 'meta_value_num');
//set_query_var('meta_type', 'numeric');
set_query_var('meta_key', $_GET['orderby']);
set_query_var('order', $order);
}
}
add_filter('pre_get_posts','wpse139657_orderby');
```
Then on my **search.php** page I used the following code for the select dropdown --
```
<select class="dropdown-class" name="sort-posts" id="sortbox" onchange="document.location.href=location.href+this.options[this.selectedIndex].value;">
<option disabled>Sort by</option>
<option value="&orderby=date&order=dsc">Newest</option>
<option value="&orderby=date&order=asc">Oldest</option>
<option value="&orderby=property_price2&order=DESC">Most Expensive</option>
<option value="&orderby=property_price2&order=ASC">Least Expensive</option>
<option value="&orderby=area2&order=DESC">Largest</option>
<option value="&orderby=area2&order=ASC">Smallest</option>
</select>
```
This seems to do the trick and works with pagination, only issues I have right now is --
>
> 1. Ugly Urls
> 2. When the page is reloaded with the posts sorted, the dropdown select goes back to default ie "Newest" when it should still be on the
> option the user chose.
>
>
> |
288,740 | <p>In my addon, I would like to check on activation, if a column of a specific table in the DB already exists to avoid to implement it for each activation.</p>
<p>Something like this :</p>
<pre><code>class MainClassAddon{
public function __construct(){
register_activation_hook( __FILE__, array( $this, 'install' ) );
}
public function install(){
if( /*Checking if column c in table wp_t exists*/ ){
$wpdb->query("ALTER TABLE wp_t ADD c INT(1) NOT NULL DEFAULT 1");
}
}
}
new MainClassAddon();
register_uninstall_hook( __FILE__, array( 'PluginNamespace\MainClassAddon', 'uninstall' ) );
</code></pre>
| [
{
"answer_id": 288741,
"author": "J.BizMai",
"author_id": 128094,
"author_profile": "https://wordpress.stackexchange.com/users/128094",
"pm_score": 2,
"selected": true,
"text": "<p>I found this solution : <a href=\"https://stackoverflow.com/questions/21330932/add-new-column-to-wordpress-database#answer-21331762\">here</a></p>\n\n<p>So...</p>\n\n<pre><code>class MainClassAddon{\n\n public function __construct(){\n register_activation_hook( __FILE__, array( $this, 'install' ) );\n }\n\n public function install(){\n\n $row = $wpdb->get_results( \"SELECT COLUMN_NAME FROM INFORMATION_SCHEMA.COLUMNS WHERE table_name = 'wp_t' AND column_name = 'c'\" );\n\n if(empty($row)){\n $wpdb->query(\"ALTER TABLE wp_t ADD c INT(1) NOT NULL DEFAULT 1\");\n }\n }\n}\nnew MainClassAddon();\nregister_uninstall_hook( __FILE__, array( 'PluginNamespace\\MainClassAddon', 'uninstall' ) );\n</code></pre>\n"
},
{
"answer_id": 414299,
"author": "Marsellus",
"author_id": 219801,
"author_profile": "https://wordpress.stackexchange.com/users/219801",
"pm_score": 0,
"selected": false,
"text": "<p>WordPress has a built-in function for this: <strong>maybe_add_column()</strong> <a href=\"https://developer.wordpress.org/reference/functions/maybe_add_column/\" rel=\"nofollow noreferrer\">https://developer.wordpress.org/reference/functions/maybe_add_column/</a></p>\n<pre><code>global $wpdb;\n$table_name = $wpdb->prefix . 'wp_t';\n$column_name = 'c';\n$create_ddl = "ALTER TABLE $table_name ADD $column_name INT(1) NOT NULL DEFAULT 1;";\n\nrequire_once(ABSPATH . 'wp-admin/includes/upgrade.php');\nmaybe_add_column($table_name, $column_name, $create_ddl);\n</code></pre>\n<p>Applying it to your solution:</p>\n<pre><code>class MainClassAddon{\n\n public function __construct(){\n register_activation_hook( __FILE__, array( $this, 'install' ) );\n }\n\n public function install(){\n global $wpdb;\n $table_name = $wpdb->prefix . 'wp_t';\n $column_name = 'c';\n $create_ddl = "ALTER TABLE $table_name ADD $column_name INT(1) NOT NULL DEFAULT 1;";\n \n require_once(ABSPATH . 'wp-admin/includes/upgrade.php');\n maybe_add_column($table_name, $column_name, $create_ddl);\n }\n}\nnew MainClassAddon();\nregister_uninstall_hook( __FILE__, array( 'PluginNamespace\\MainClassAddon', 'uninstall' ) );\n</code></pre>\n"
}
]
| 2017/12/15 | [
"https://wordpress.stackexchange.com/questions/288740",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/128094/"
]
| In my addon, I would like to check on activation, if a column of a specific table in the DB already exists to avoid to implement it for each activation.
Something like this :
```
class MainClassAddon{
public function __construct(){
register_activation_hook( __FILE__, array( $this, 'install' ) );
}
public function install(){
if( /*Checking if column c in table wp_t exists*/ ){
$wpdb->query("ALTER TABLE wp_t ADD c INT(1) NOT NULL DEFAULT 1");
}
}
}
new MainClassAddon();
register_uninstall_hook( __FILE__, array( 'PluginNamespace\MainClassAddon', 'uninstall' ) );
``` | I found this solution : [here](https://stackoverflow.com/questions/21330932/add-new-column-to-wordpress-database#answer-21331762)
So...
```
class MainClassAddon{
public function __construct(){
register_activation_hook( __FILE__, array( $this, 'install' ) );
}
public function install(){
$row = $wpdb->get_results( "SELECT COLUMN_NAME FROM INFORMATION_SCHEMA.COLUMNS WHERE table_name = 'wp_t' AND column_name = 'c'" );
if(empty($row)){
$wpdb->query("ALTER TABLE wp_t ADD c INT(1) NOT NULL DEFAULT 1");
}
}
}
new MainClassAddon();
register_uninstall_hook( __FILE__, array( 'PluginNamespace\MainClassAddon', 'uninstall' ) );
``` |
288,769 | <p>My client explicitly does not want to use 'multisite' wordpress option. <br>
My client has a main site and 199 sub sites (other domains). <br>
A user has usermeta with meta key: branch_id <br></p>
<p>As an example (completely made up names): <br>
Main site: kero.com <br>
Sub site: uka.com (and many others) <br></p>
<p>Both domains have SSL certificates.</p>
<p>The end goal is as following:
When you log in to the main site (kero.com). I have build a plugin which checks which branch ID is attached to the user. It goes like this:</p>
<pre><code>function myplugin_auth_signon( $username, $password ) {
$user = get_user_by('email', $username);
$user_id = $user->ID;
$key = 'branch_id';
$single = true;
$branch = get_user_meta( $user_id, $key, $single );
if($branch == 'number') {
//magic happens here!
$cookie = "cookie.txt";
$postdata = "log=" . $username . "&pwd=" . $password . "&wp-submit=Log%20In&redirect_to=" . $url . "wp-admin/&testcookie=1";
$ch = curl_init();
curl_setopt ($ch, CURLOPT_URL, $url . "wp-login.php");
curl_setopt ($ch, CURLOPT_SSL_VERIFYPEER, FALSE);
curl_setopt ($ch, CURLOPT_USERAGENT, "Mozilla/5.0 (Windows; U; Windows NT 5.1; en-US; rv:1.8.1.6) Gecko/20070725 Firefox/2.0.0.6");
curl_setopt ($ch, CURLOPT_TIMEOUT, 60);
curl_setopt ($ch, CURLOPT_FOLLOWLOCATION, 1);
curl_setopt ($ch, CURLOPT_RETURNTRANSFER, 0);
curl_setopt ($ch, CURLOPT_COOKIEJAR, $cookie);
curl_setopt ($ch, CURLOPT_COOKIEFILE, $cookie);
curl_setopt ($ch, CURLOPT_REFERER, $url . "wp-login.php");
curl_setopt ($ch, CURLOPT_POSTFIELDS, $postdata);
curl_setopt ($ch, CURLOPT_POST, 1);
$result = curl_exec ($ch);
curl_close($ch);
//This is from the answer of the link. On the end url the users get redirected from wp-admin to my-account
header('location: ' . $url . 'wp-admin/');
die();
//after logging in redirect the user to uka.com/my-account
}
add_action( 'wp_authenticate', 'myplugin_auth_signon', 30, 2 );
</code></pre>
<p>So I build all kind of stuff, I used this link on the //magic happens here:
<a href="https://stackoverflow.com/questions/728274/php-curl-post-to-login-to-wordpress">Click here.</a></p>
<p>It does not work as intented. It keeps me on the main website, but when I click on 'store' it is in the sub site. When I go to my-account (where I should be logged in) i'm not logged in anymore.</p>
<p>I wrote some other code:</p>
<pre><code>$response = wp_remote_post( $url, array(
'method' => 'POST',
'timeout' => 45,
'redirection' => 5,
'httpversion' => '1.0',
'blocking' => true,
'headers' => array(),
'body' => array(
'username' => $username,
'password' => $password
),
'cookies' => array()
)
);
</code></pre>
<p>I don't really know how to use this for my personal goal. I can echo the results, but then get a big array of headers etc. And when I surf to the subsite: I'm not logged in... So it just does not keep sessions/cookies.</p>
<p>TBH: I'm really a beginner on the whole session/cookie/security stuff. Most of the time I build in Wordpress or Laravel and most of the security stuff is already handled then.</p>
<p>Thanks everyone who is taking the time to read this.</p>
<p><strong>UPDATE: Added extra cUrl code!</strong></p>
| [
{
"answer_id": 288808,
"author": "Mark Kaplun",
"author_id": 23970,
"author_profile": "https://wordpress.stackexchange.com/users/23970",
"pm_score": 1,
"selected": false,
"text": "<p>You can not set cookies form site A that will be applicable on site B, therefor your \"login by proxy\" scheme will not work, and can not be made to work. In addition storing passwords in plain text is just a big no-no.</p>\n"
},
{
"answer_id": 288959,
"author": "majick",
"author_id": 76440,
"author_profile": "https://wordpress.stackexchange.com/users/76440",
"pm_score": 1,
"selected": false,
"text": "<p>I think it would be <em>possible</em> to do it safely by doing something like this:</p>\n\n<ol>\n<li>Within the authenticate filter, send the CURL request as you are doing. The username / password would have to match (be synced) between site and subsite.</li>\n<li>Now logged in to the subsite, send a second CURL request to the subsite to get a temporary authentication token (generated by custom code on the subsite.)</li>\n<li>Put an iframe on the original site page (the one redirected to after logging in)... with the iframe <code>src</code> set to the subsite, with the temporary code (and username) sent in the querystring. (Alternatively just redirect to the subsite with the same URL.)</li>\n<li>Have custom code on the subsite to recognize the temporary authentication code (combined with username) and generate the authentication cookies that would be made in a normal login. </li>\n</ol>\n\n<p>End result, the login cookie is set in the client's browser for the subsite as desired. :-)</p>\n"
},
{
"answer_id": 293502,
"author": "Dennis86",
"author_id": 131414,
"author_profile": "https://wordpress.stackexchange.com/users/131414",
"pm_score": 1,
"selected": true,
"text": "<p>For future reference I am answering my own question.\nDisclaimer: This was a freelance gig and had to be done in a X time frame.\nWhich mean that this was the quickest AND simplest option.</p>\n\n<p>What I did was: </p>\n\n<ol>\n<li>Installed the plugin <a href=\"https://wordpress.org/plugins/user-session-synchronizer/\" rel=\"nofollow noreferrer\">https://wordpress.org/plugins/user-session-synchronizer/</a> - Give this guy some credit, this plugin is insanely good. Besides the insane fact that it's FREE...</li>\n<li>I hooked in on the wp_loaded hook and checked what branch ID the user had; The plugin I wrote had options with branch ID's and the urls. It So after checking what branch ID the user had: it checked which url corresponded with the branch ID. </li>\n</ol>\n\n<p>Then echo'd</p>\n\n<pre><code>echo \"<script>setTimeout(function() { parent.self.location='https://server.com'; }, 1500);</script>\";\n</code></pre>\n"
}
]
| 2017/12/16 | [
"https://wordpress.stackexchange.com/questions/288769",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/131414/"
]
| My client explicitly does not want to use 'multisite' wordpress option.
My client has a main site and 199 sub sites (other domains).
A user has usermeta with meta key: branch\_id
As an example (completely made up names):
Main site: kero.com
Sub site: uka.com (and many others)
Both domains have SSL certificates.
The end goal is as following:
When you log in to the main site (kero.com). I have build a plugin which checks which branch ID is attached to the user. It goes like this:
```
function myplugin_auth_signon( $username, $password ) {
$user = get_user_by('email', $username);
$user_id = $user->ID;
$key = 'branch_id';
$single = true;
$branch = get_user_meta( $user_id, $key, $single );
if($branch == 'number') {
//magic happens here!
$cookie = "cookie.txt";
$postdata = "log=" . $username . "&pwd=" . $password . "&wp-submit=Log%20In&redirect_to=" . $url . "wp-admin/&testcookie=1";
$ch = curl_init();
curl_setopt ($ch, CURLOPT_URL, $url . "wp-login.php");
curl_setopt ($ch, CURLOPT_SSL_VERIFYPEER, FALSE);
curl_setopt ($ch, CURLOPT_USERAGENT, "Mozilla/5.0 (Windows; U; Windows NT 5.1; en-US; rv:1.8.1.6) Gecko/20070725 Firefox/2.0.0.6");
curl_setopt ($ch, CURLOPT_TIMEOUT, 60);
curl_setopt ($ch, CURLOPT_FOLLOWLOCATION, 1);
curl_setopt ($ch, CURLOPT_RETURNTRANSFER, 0);
curl_setopt ($ch, CURLOPT_COOKIEJAR, $cookie);
curl_setopt ($ch, CURLOPT_COOKIEFILE, $cookie);
curl_setopt ($ch, CURLOPT_REFERER, $url . "wp-login.php");
curl_setopt ($ch, CURLOPT_POSTFIELDS, $postdata);
curl_setopt ($ch, CURLOPT_POST, 1);
$result = curl_exec ($ch);
curl_close($ch);
//This is from the answer of the link. On the end url the users get redirected from wp-admin to my-account
header('location: ' . $url . 'wp-admin/');
die();
//after logging in redirect the user to uka.com/my-account
}
add_action( 'wp_authenticate', 'myplugin_auth_signon', 30, 2 );
```
So I build all kind of stuff, I used this link on the //magic happens here:
[Click here.](https://stackoverflow.com/questions/728274/php-curl-post-to-login-to-wordpress)
It does not work as intented. It keeps me on the main website, but when I click on 'store' it is in the sub site. When I go to my-account (where I should be logged in) i'm not logged in anymore.
I wrote some other code:
```
$response = wp_remote_post( $url, array(
'method' => 'POST',
'timeout' => 45,
'redirection' => 5,
'httpversion' => '1.0',
'blocking' => true,
'headers' => array(),
'body' => array(
'username' => $username,
'password' => $password
),
'cookies' => array()
)
);
```
I don't really know how to use this for my personal goal. I can echo the results, but then get a big array of headers etc. And when I surf to the subsite: I'm not logged in... So it just does not keep sessions/cookies.
TBH: I'm really a beginner on the whole session/cookie/security stuff. Most of the time I build in Wordpress or Laravel and most of the security stuff is already handled then.
Thanks everyone who is taking the time to read this.
**UPDATE: Added extra cUrl code!** | For future reference I am answering my own question.
Disclaimer: This was a freelance gig and had to be done in a X time frame.
Which mean that this was the quickest AND simplest option.
What I did was:
1. Installed the plugin <https://wordpress.org/plugins/user-session-synchronizer/> - Give this guy some credit, this plugin is insanely good. Besides the insane fact that it's FREE...
2. I hooked in on the wp\_loaded hook and checked what branch ID the user had; The plugin I wrote had options with branch ID's and the urls. It So after checking what branch ID the user had: it checked which url corresponded with the branch ID.
Then echo'd
```
echo "<script>setTimeout(function() { parent.self.location='https://server.com'; }, 1500);</script>";
``` |
288,776 | <p>This is my array of image URL's added to the same custom field named images.</p>
<pre><code> $images = get_post_custom_values( 'images' );
</code></pre>
<p>I need to print all these images in a template file.</p>
| [
{
"answer_id": 288780,
"author": "Cyclonecode",
"author_id": 14870,
"author_profile": "https://wordpress.stackexchange.com/users/14870",
"pm_score": 2,
"selected": false,
"text": "<p>Since you are storing an url for each image you can create a query to get the id of the attachment based on the <code>guid</code>:</p>\n\n<pre><code>global $wpdb;\n$ids = array();\nforeach ($images as $image_url) {\n $ids[] = $wpdb->get_col($wpdb->prepare(\"SELECT ID FROM $wpdb->posts WHERE guid='%s';\", $image_url));\n}\n</code></pre>\n\n<p>Another way would be to simply store the <code>ID</code> rather than the url in your custom field, then there would not be necessary to perform a the above query for each image.</p>\n"
},
{
"answer_id": 288867,
"author": "Dev",
"author_id": 104464,
"author_profile": "https://wordpress.stackexchange.com/users/104464",
"pm_score": 2,
"selected": true,
"text": "<p>This is how i ended up coding the solution :</p>\n\n<pre><code>$images = get_post_custom_values( 'images' );\n\nif ( $images ) {\n\n echo '<div class=\"image-wrap\">';\n\n if ( $image_header ) {\n echo '<div class=\"header\">' . esc_html( $image_header ) . '</div>';\n }\n\n foreach ( (array) $images as $image ) {\n\n $url = esc_url( $image );\n $alt = esc_html( the_title_attribute( 'echo=0' ) );\n\n if ( $url ) {\n echo '<img class=\"image-section\" src=\"' . $url . '\" alt=\"' . $alt . '\" />';\n }\n\n }\n\n echo '</div>';\n\n}\n</code></pre>\n\n<p><strong>To get the i.d from a URL</strong></p>\n\n<p>You can use <a href=\"https://developer.wordpress.org/reference/functions/attachment_url_to_postid/\" rel=\"nofollow noreferrer\">attachment_url_to_postid</a> like this :</p>\n\n<pre><code>$url = 'http://example.com/img.png';\n$id = attachment_url_to_postid( $url );\n$alt = get_post_meta( $id, '_wp_attachment_image_alt', true );\n</code></pre>\n"
}
]
| 2017/12/16 | [
"https://wordpress.stackexchange.com/questions/288776",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/104464/"
]
| This is my array of image URL's added to the same custom field named images.
```
$images = get_post_custom_values( 'images' );
```
I need to print all these images in a template file. | This is how i ended up coding the solution :
```
$images = get_post_custom_values( 'images' );
if ( $images ) {
echo '<div class="image-wrap">';
if ( $image_header ) {
echo '<div class="header">' . esc_html( $image_header ) . '</div>';
}
foreach ( (array) $images as $image ) {
$url = esc_url( $image );
$alt = esc_html( the_title_attribute( 'echo=0' ) );
if ( $url ) {
echo '<img class="image-section" src="' . $url . '" alt="' . $alt . '" />';
}
}
echo '</div>';
}
```
**To get the i.d from a URL**
You can use [attachment\_url\_to\_postid](https://developer.wordpress.org/reference/functions/attachment_url_to_postid/) like this :
```
$url = 'http://example.com/img.png';
$id = attachment_url_to_postid( $url );
$alt = get_post_meta( $id, '_wp_attachment_image_alt', true );
``` |
288,781 | <p>I am trying to debug a plugin and am using <code>error_log()</code> in various places to see what various things are. I am using the following:</p>
<pre><code>error_log( print_r( $variable ) );
</code></pre>
<p>When I look at <code>debug.log</code>, all I see is <code>1</code> and the actual output of the <code>error_log()</code> function is sent to the browser instead.</p>
<p>I know another plugin is not doing this as all are disabled with the exception of the one I am writing. In my <code>wp-config.php</code>, I have defined <code>WP_DEBUG_DISPLAY</code> as <code>false</code>.</p>
<p>The same thing happens if I use <code>var_dump()</code> and <code>var_export()</code>. Other functions like <code>gettype()</code> work just fine.</p>
<p>Is there any way to get the output into <code>debug.log</code>?</p>
| [
{
"answer_id": 288782,
"author": "Shibi",
"author_id": 62500,
"author_profile": "https://wordpress.stackexchange.com/users/62500",
"pm_score": 5,
"selected": true,
"text": "<p>The <a href=\"http://php.net/manual/en/function.print-r.php\" rel=\"noreferrer\">print_r</a> function accept second parameter for <code>return</code> so it retrun the variable instead of printing it.</p>\n\n<pre><code>print_r($expression, $return)\n</code></pre>\n\n<p>So you can do</p>\n\n<pre><code>error_log( print_r( $variable, true ) );\n</code></pre>\n"
},
{
"answer_id": 288797,
"author": "Johansson",
"author_id": 94498,
"author_profile": "https://wordpress.stackexchange.com/users/94498",
"pm_score": 2,
"selected": false,
"text": "<p>If your variable is just a string, then you can simply use <code>error_log ( $variable )</code>. If it's an object or an array, other than using <code>print_r()</code>, you can serialize it too:</p>\n\n<pre><code>error_log ( serialize ( $variable ) );\n</code></pre>\n"
},
{
"answer_id": 357716,
"author": "butlerblog",
"author_id": 38603,
"author_profile": "https://wordpress.stackexchange.com/users/38603",
"pm_score": 0,
"selected": false,
"text": "<p>While the accepted answer is correct, I wanted to include an answer that expands the explanation for clarity.</p>\n\n<p><code>print_r()</code> accepts two arguments (<a href=\"https://www.php.net/manual/en/function.print-r.php\" rel=\"nofollow noreferrer\">see the documentation for this function</a>), the second of which is optional and you have omitted. The first argument is the expression to be printed. The second specifies whether the value is returned or printed.</p>\n\n<p>When the second argument is omitted, its default value is <code>false</code> and therefore it prints the result immediately. If this argument is false, <code>print_r()</code> will return <code>true</code> (which is displayed as \"1\" in the error log).</p>\n\n<pre><code>$result = print_r( $variable );\n</code></pre>\n\n<p>The returned result here is <code>true</code> (displayed as \"1\").</p>\n\n<p>You're passing the returned result of <code>print_r()</code> to <code>error_log()</code>. For the reason described above, this result is \"1\" and that is why you're getting 1 as the entry in the log.</p>\n\n<p>In order to get a result to contain the expression in <code>$variable</code> and pass it to the <code>error_log()</code> function, you need <code>print_r()</code> to return the expression as the result. You can do that by specifying the second argument as TRUE.</p>\n\n<pre><code>$result = print_r( $variable, true );\n</code></pre>\n\n<p>Now the returned result of <code>print_r()</code> is the expression contained in <code>$variable</code> and you can pass it to <code>error_log()</code>:</p>\n\n<pre><code>$result = print_r( $variable, true );\nerror_log( $result );\n</code></pre>\n\n<p><strong><em>OR:</em></strong></p>\n\n<pre><code>error_log( print_r( $variable, true ) );\n</code></pre>\n\n<p>If you want to take this a step further, you could write a utility function for writing to the log that would handle determining if <code>$variable</code> was an array or an object and thus required <code>print_r()</code>, or if it could simply be passed as a string. This makes it easy to handle debug logging since you don't have to be concerned with the variable type in order to pass it for logging. I have written such <a href=\"https://wpbitz.com/utility-function-for-the-wordpress-error-log/\" rel=\"nofollow noreferrer\">a utility along with a detailed explanation here</a>. </p>\n\n<p><strong>Side note on the PHP functions you mentioned:</strong> No matter how experienced you are, it's always helpful to review the documentation of the functions you are using in order to make sure you know what they actually do. I have linked to the <code>print_r()</code> documentation above, which describes exactly what was talked about in both this <em>and</em> the accepted answer. But also mentioned were some other PHP functions that worked or didn't work. Let's consider those:</p>\n\n<p><a href=\"https://www.php.net/manual/en/function.var-dump.php\" rel=\"nofollow noreferrer\"><code>var_dump()</code></a>: The documentation indicates that this function does not return a result. In order to pass something to <code>error_log()</code> for including in the error log, it needs to be an expression contained in a variable. This function does not return anything, it only outputs to the screen. So you can't use it to pass anything to <code>error_log()</code>.</p>\n\n<p><a href=\"https://www.php.net/manual/en/function.var-export.php\" rel=\"nofollow noreferrer\"><code>var_export()</code></a>: Similar to <code>print_r()</code> in that you have a second, optional argument to either return a result or print to the screen. Define the second argument as <code>true</code> to be able to return a result for <code>error_log()</code>.</p>\n\n<p><a href=\"https://www.php.net/manual/en/function.gettype.php\" rel=\"nofollow noreferrer\"><code>gettype()</code></a> always returns the type of the variable. So you have something you can pass to <code>error_log()</code> by default. That is why it worked.</p>\n"
}
]
| 2017/12/16 | [
"https://wordpress.stackexchange.com/questions/288781",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/80069/"
]
| I am trying to debug a plugin and am using `error_log()` in various places to see what various things are. I am using the following:
```
error_log( print_r( $variable ) );
```
When I look at `debug.log`, all I see is `1` and the actual output of the `error_log()` function is sent to the browser instead.
I know another plugin is not doing this as all are disabled with the exception of the one I am writing. In my `wp-config.php`, I have defined `WP_DEBUG_DISPLAY` as `false`.
The same thing happens if I use `var_dump()` and `var_export()`. Other functions like `gettype()` work just fine.
Is there any way to get the output into `debug.log`? | The [print\_r](http://php.net/manual/en/function.print-r.php) function accept second parameter for `return` so it retrun the variable instead of printing it.
```
print_r($expression, $return)
```
So you can do
```
error_log( print_r( $variable, true ) );
``` |
288,793 | <p>I making homepage in the local host.</p>
<p>I need <code>wp_query</code> with Ajax.</p>
<p>but there's some error. I don't know why. Can you help me?</p>
<p>----> this is <code>load_more_ajax.js</code></p>
<pre><code>var page = 2;
var date_pass = "<?php echo($date_filter);?>";
var compare_pass = "<?php echo($compare);?>";
var ajaxurl = "<?php echo admin_url( 'admin-ajax.php' ); ?>";
jQuery(function($){
$('body').on('click', '.loadmore', function(){
var data = {
'action': 'rnm_load_more_ajax',
'page': page,
'date_filter': date_pass,
'compare': compare_pass,
'security': '<?php echo wp_create_nonce("load_more_posts"); ?>'
};
$.post(ajaxurl, data, function(response){
$('.race-posts').append(response);
page++;
});
});
});
</code></pre>
<p>and, this is <code>load_more_ajax.php</code></p>
<pre><code><?php
function load_posts_by_ajax_callback(){
echo ("hello");
}
</code></pre>
<p>this is add_action</p>
<pre><code>add_action('wp_ajax_rnm_load_more_ajax', 'load_posts_by_ajax_callback');
add_action('wp_ajax_nopriv_rnm_load_more_ajax', 'load_posts_by_ajax_callback');
add_action('wp_enqueue_scripts', 'rnm_enqueue_fn');
function rnm_enqueue_fn(){
wp_register_script('rnm_load_more', get_template_directory_uri() .'/js/load_more_ajax.js', array(), false, true);
wp_enqueue_script('rnm_load_more');
}
</code></pre>
<p>This makes error like this.
<a href="https://i.stack.imgur.com/2emED.jpg" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/2emED.jpg" alt="error message"></a></p>
<p>I think there's some problem in the url of 'admin-ajax.php'</p>
<p>But I can't find any solution. </p>
| [
{
"answer_id": 288795,
"author": "janh",
"author_id": 129206,
"author_profile": "https://wordpress.stackexchange.com/users/129206",
"pm_score": 0,
"selected": false,
"text": "<p>You can't use PHP code in a .js file, unless you change your config. Even if you did, you'd also have to load WP to get those URLs. What is happening right now is that you have the PHP code, and not its result, in the JS.</p>\n\n<p>You'll probably want to use <a href=\"https://codex.wordpress.org/Function_Reference/wp_localize_script\" rel=\"nofollow noreferrer\">wp_localize_script</a> to set data from WP that you can then access in a static JavaScript file.</p>\n"
},
{
"answer_id": 288796,
"author": "Johansson",
"author_id": 94498,
"author_profile": "https://wordpress.stackexchange.com/users/94498",
"pm_score": 2,
"selected": true,
"text": "<p>You need to pass the values to the localization script, <em>\"right\"</em> after this line:</p>\n\n<pre><code>wp_enqueue_script('rnm_load_more');\n</code></pre>\n\n<p>I'm going to pass the admin URL to your script by using <a href=\"https://codex.wordpress.org/Function_Reference/wp_localize_script\" rel=\"nofollow noreferrer\"><code>wp_localize_script</code></a>:</p>\n\n<pre><code>$localization = array(\n 'ajax_url' => admin_url('admin-ajax.php'),\n);\nwp_localize_script( 'rnm_load_more', 'jjang', $localization );\n</code></pre>\n\n<p>Now, you can use the <code>ajax_url</code> in your script:</p>\n\n<pre><code>var ajaxurl = rnm_load_more.ajax_url;\n</code></pre>\n\n<p>You can send the rest of the data by using this method.</p>\n"
}
]
| 2017/12/17 | [
"https://wordpress.stackexchange.com/questions/288793",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/133185/"
]
| I making homepage in the local host.
I need `wp_query` with Ajax.
but there's some error. I don't know why. Can you help me?
----> this is `load_more_ajax.js`
```
var page = 2;
var date_pass = "<?php echo($date_filter);?>";
var compare_pass = "<?php echo($compare);?>";
var ajaxurl = "<?php echo admin_url( 'admin-ajax.php' ); ?>";
jQuery(function($){
$('body').on('click', '.loadmore', function(){
var data = {
'action': 'rnm_load_more_ajax',
'page': page,
'date_filter': date_pass,
'compare': compare_pass,
'security': '<?php echo wp_create_nonce("load_more_posts"); ?>'
};
$.post(ajaxurl, data, function(response){
$('.race-posts').append(response);
page++;
});
});
});
```
and, this is `load_more_ajax.php`
```
<?php
function load_posts_by_ajax_callback(){
echo ("hello");
}
```
this is add\_action
```
add_action('wp_ajax_rnm_load_more_ajax', 'load_posts_by_ajax_callback');
add_action('wp_ajax_nopriv_rnm_load_more_ajax', 'load_posts_by_ajax_callback');
add_action('wp_enqueue_scripts', 'rnm_enqueue_fn');
function rnm_enqueue_fn(){
wp_register_script('rnm_load_more', get_template_directory_uri() .'/js/load_more_ajax.js', array(), false, true);
wp_enqueue_script('rnm_load_more');
}
```
This makes error like this.
[](https://i.stack.imgur.com/2emED.jpg)
I think there's some problem in the url of 'admin-ajax.php'
But I can't find any solution. | You need to pass the values to the localization script, *"right"* after this line:
```
wp_enqueue_script('rnm_load_more');
```
I'm going to pass the admin URL to your script by using [`wp_localize_script`](https://codex.wordpress.org/Function_Reference/wp_localize_script):
```
$localization = array(
'ajax_url' => admin_url('admin-ajax.php'),
);
wp_localize_script( 'rnm_load_more', 'jjang', $localization );
```
Now, you can use the `ajax_url` in your script:
```
var ajaxurl = rnm_load_more.ajax_url;
```
You can send the rest of the data by using this method. |
288,804 | <p>I have a custom function in functions.php that excludes specific category from the category list:</p>
<pre><code>function incomplete_cat_list() {
$first_time = 1;
foreach((get_the_category()) as $category) {
if ($category->cat_name != 'Category Name') {
if ($first_time == 1) {
echo '<a class="cat-list" href="' . get_category_link(
$category->term_id ) . '" title="' . sprintf( __( "See all %s" ),
$category->name ) . '" ' . '>' . $category->name.'</a>';
$first_time = 0;
}
else {
}
}
}
}
</code></pre>
<p>I would like to use it in related posts foreach loop, but I'm not sure how to do it... Here's the code for displaying related posts by tags or category:</p>
<pre><code> <?php
$max_articles = 4; // How many articles to display
echo '<div id="related-articles" class="relatedposts"><h3>Related articles</h3>';
$cnt = 0;
$article_tags = get_the_tags();
$tags_string = '';
if ($article_tags) {
foreach ($article_tags as $article_tag) {
$tags_string .= $article_tag->slug . ',';
}
}
$tag_related_posts = get_posts('exclude=' . $post->ID . '&numberposts=' . $max_articles . '&tag=' . $tags_string);
if ($tag_related_posts) {
foreach ($tag_related_posts as $related_post) {
$cnt++;
echo '<div class="child-' . $cnt . '">';
echo '<a href="' . get_permalink($related_post->ID) . '">';
echo get_the_post_thumbnail($related_post->ID);
echo $related_post->post_title . '</a>';
echo incomplete_cat_list;
echo '</div>';
}
}
// Only if there's not enough tag related articles,
// we add some from the same category
if ($cnt < $max_articles) {
$article_categories = get_the_category($post->ID);
$category_string = '';
foreach($article_categories as $category) {
$category_string .= $category->cat_ID . ',';
}
$cat_related_posts = get_posts('exclude=' . $post->ID . '&numberposts=' . $max_articles . '&category=' . $category_string);
if ($cat_related_posts) {
foreach ($cat_related_posts as $related_post) {
$cnt++;
if ($cnt > $max_articles) break;
echo '<div class="child-' . $cnt . '">';
echo '<a href="' . get_permalink($related_post->ID) . '">';
echo get_the_post_thumbnail($related_post->ID);
echo $related_post->post_title . '</a>';
echo incomplete_cat_list;
echo '</div>';
}
}
}
echo '</div>';
?>
</code></pre>
<p><strong>How to call the custom function from functions.php inside above loop?</strong></p>
| [
{
"answer_id": 288805,
"author": "Shibi",
"author_id": 62500,
"author_profile": "https://wordpress.stackexchange.com/users/62500",
"pm_score": 2,
"selected": true,
"text": "<p>First you need to pass the post_id to this function to use the post_id inside the <code>get_the_category($post_id)</code></p>\n\n<pre><code>function incomplete_cat_list($post_id = '') {\n global $post;\n $post_id = ($post_id) ? $post_id : $post->ID;\n $first_time = 1;\n $categories = get_the_category($post_id);\n foreach($categories as $category) {\n if ($category->cat_name != 'Category Name') {\n if ($first_time == 1) {\n echo '<a class=\"cat-list\" href=\"' . get_category_link( \n $category->term_id ) . '\" title=\"' . sprintf( __( \"See all %s\" ), \n $category->name ) . '\" ' . '>' . $category->name.'</a>';\n $first_time = 0;\n }\n else {\n }\n }\n }\n}\n</code></pre>\n\n<p>This function already <code>echo</code> so you don't need to echo it again. So you should call it like this.</p>\n\n<pre><code>incomplete_cat_list($related_post->ID);\n</code></pre>\n\n<p>Another thing if you want to stop the loop after you get the first category instead of using this <code>$first_time</code> variable just use <code>break;</code> to stop the loop.</p>\n"
},
{
"answer_id": 288814,
"author": "Anda",
"author_id": 133403,
"author_profile": "https://wordpress.stackexchange.com/users/133403",
"pm_score": 0,
"selected": false,
"text": "<p>@Shibi, for your tip about using <code>break</code> - this is how the function should look?</p>\n\n<pre><code>// Exclude category name from carousel\nfunction incomplete_cat_list($post_id = '') {\nglobal $post;\n$post_id = ($post_id) ? $post_id : $post->ID;\n$categories = get_the_category($post_id);\nforeach($categories as $category) {\n if ($category->cat_name != 'Category name') {\n echo '<a class=\"cat-list\" href=\"' . \n get_category_link( \n $category->term_id ) . '\" title=\"' . sprintf( __( \"See all in %s\" ), \n $category->name ) . '\" ' . '>' . $category->name.'</a>';\n break;\n }\n}\n}\n</code></pre>\n"
}
]
| 2017/12/17 | [
"https://wordpress.stackexchange.com/questions/288804",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/133403/"
]
| I have a custom function in functions.php that excludes specific category from the category list:
```
function incomplete_cat_list() {
$first_time = 1;
foreach((get_the_category()) as $category) {
if ($category->cat_name != 'Category Name') {
if ($first_time == 1) {
echo '<a class="cat-list" href="' . get_category_link(
$category->term_id ) . '" title="' . sprintf( __( "See all %s" ),
$category->name ) . '" ' . '>' . $category->name.'</a>';
$first_time = 0;
}
else {
}
}
}
}
```
I would like to use it in related posts foreach loop, but I'm not sure how to do it... Here's the code for displaying related posts by tags or category:
```
<?php
$max_articles = 4; // How many articles to display
echo '<div id="related-articles" class="relatedposts"><h3>Related articles</h3>';
$cnt = 0;
$article_tags = get_the_tags();
$tags_string = '';
if ($article_tags) {
foreach ($article_tags as $article_tag) {
$tags_string .= $article_tag->slug . ',';
}
}
$tag_related_posts = get_posts('exclude=' . $post->ID . '&numberposts=' . $max_articles . '&tag=' . $tags_string);
if ($tag_related_posts) {
foreach ($tag_related_posts as $related_post) {
$cnt++;
echo '<div class="child-' . $cnt . '">';
echo '<a href="' . get_permalink($related_post->ID) . '">';
echo get_the_post_thumbnail($related_post->ID);
echo $related_post->post_title . '</a>';
echo incomplete_cat_list;
echo '</div>';
}
}
// Only if there's not enough tag related articles,
// we add some from the same category
if ($cnt < $max_articles) {
$article_categories = get_the_category($post->ID);
$category_string = '';
foreach($article_categories as $category) {
$category_string .= $category->cat_ID . ',';
}
$cat_related_posts = get_posts('exclude=' . $post->ID . '&numberposts=' . $max_articles . '&category=' . $category_string);
if ($cat_related_posts) {
foreach ($cat_related_posts as $related_post) {
$cnt++;
if ($cnt > $max_articles) break;
echo '<div class="child-' . $cnt . '">';
echo '<a href="' . get_permalink($related_post->ID) . '">';
echo get_the_post_thumbnail($related_post->ID);
echo $related_post->post_title . '</a>';
echo incomplete_cat_list;
echo '</div>';
}
}
}
echo '</div>';
?>
```
**How to call the custom function from functions.php inside above loop?** | First you need to pass the post\_id to this function to use the post\_id inside the `get_the_category($post_id)`
```
function incomplete_cat_list($post_id = '') {
global $post;
$post_id = ($post_id) ? $post_id : $post->ID;
$first_time = 1;
$categories = get_the_category($post_id);
foreach($categories as $category) {
if ($category->cat_name != 'Category Name') {
if ($first_time == 1) {
echo '<a class="cat-list" href="' . get_category_link(
$category->term_id ) . '" title="' . sprintf( __( "See all %s" ),
$category->name ) . '" ' . '>' . $category->name.'</a>';
$first_time = 0;
}
else {
}
}
}
}
```
This function already `echo` so you don't need to echo it again. So you should call it like this.
```
incomplete_cat_list($related_post->ID);
```
Another thing if you want to stop the loop after you get the first category instead of using this `$first_time` variable just use `break;` to stop the loop. |
288,831 | <p>In my archive I have tipical loop</p>
<pre><code>if ( have_posts() ) :
/* Start the Loop */
while ( have_posts() ) : the_post();
get_template_part( 'template-parts/content', get_post_format() );
endwhile;
wp_reset_postdata();
else :
get_template_part( 'template-parts/content', 'none' );
endif;
</code></pre>
<p>And in my sidebar I have a plugin widget which also calls new wp_query to display the recent posts.</p>
<pre><code>$query = new WP_Query(
apply_filters(
'widget_posts_args',
array(
'posts_per_page' => $number,
'no_found_rows' => true,
'post_status' => 'publish',
'ignore_sticky_posts' => true
)
)
);
</code></pre>
<p>So far so good. But then I need to add filter for my categories to display and custom posts types: </p>
<pre><code>function mvp_add_custom_types( $query ) {
if( is_category() || is_tag() || is_date() && empty( $query->query_vars['suppress_filters'] ) ) {
$query->set( 'post_type', array(
'post', 'nav_menu_item', 'mvp_projects'
));
return $query;
}
}
add_filter( 'pre_get_posts', 'mvp_add_custom_types' );
</code></pre>
<p>Which suddenly starting to break the other query.
How can I use both of this queries with the filter applied to only theme related(the other query is from a plugin)?</p>
| [
{
"answer_id": 288837,
"author": "WhirledPress",
"author_id": 133443,
"author_profile": "https://wordpress.stackexchange.com/users/133443",
"pm_score": 1,
"selected": false,
"text": "<p>I'm not entirely sure, but it looks like you need another conditional in your filter. Right now, it filters all content looking for category, tag or date that don't have the nav_menu_item, mvp_projecvts query variable set for post types. Perhaps you could add a filter to check if some variable is set and only filter if the variable exists.</p>\n\n<p>$archive_ok= true;\n then in your filter:\nif ($archive_ok) { do stuff }\n$archive_ok=false;</p>\n\n<p>It's a clunky solution and I am sure there are better answers, but it might work in a pinch.</p>\n"
},
{
"answer_id": 288926,
"author": "worldwildwebdev",
"author_id": 48915,
"author_profile": "https://wordpress.stackexchange.com/users/48915",
"pm_score": 1,
"selected": true,
"text": "<p>I got this sorted, by adding additional contional statement and wrapped OR statements in brackets: </p>\n\n<pre><code>function mvp_add_custom_types( $query ) {\n if( ( is_category() || is_tag() || is_date() ) && $query->is_main_query() && empty( $query->query_vars['suppress_filters'] ) ) {\n $query->set( 'post_type', array(\n 'post', 'nav_menu_item', 'mvp_projects'\n ));\n return $query;\n }\n}\nadd_filter( 'pre_get_posts', 'mvp_add_custom_types' );\n</code></pre>\n"
}
]
| 2017/12/17 | [
"https://wordpress.stackexchange.com/questions/288831",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/48915/"
]
| In my archive I have tipical loop
```
if ( have_posts() ) :
/* Start the Loop */
while ( have_posts() ) : the_post();
get_template_part( 'template-parts/content', get_post_format() );
endwhile;
wp_reset_postdata();
else :
get_template_part( 'template-parts/content', 'none' );
endif;
```
And in my sidebar I have a plugin widget which also calls new wp\_query to display the recent posts.
```
$query = new WP_Query(
apply_filters(
'widget_posts_args',
array(
'posts_per_page' => $number,
'no_found_rows' => true,
'post_status' => 'publish',
'ignore_sticky_posts' => true
)
)
);
```
So far so good. But then I need to add filter for my categories to display and custom posts types:
```
function mvp_add_custom_types( $query ) {
if( is_category() || is_tag() || is_date() && empty( $query->query_vars['suppress_filters'] ) ) {
$query->set( 'post_type', array(
'post', 'nav_menu_item', 'mvp_projects'
));
return $query;
}
}
add_filter( 'pre_get_posts', 'mvp_add_custom_types' );
```
Which suddenly starting to break the other query.
How can I use both of this queries with the filter applied to only theme related(the other query is from a plugin)? | I got this sorted, by adding additional contional statement and wrapped OR statements in brackets:
```
function mvp_add_custom_types( $query ) {
if( ( is_category() || is_tag() || is_date() ) && $query->is_main_query() && empty( $query->query_vars['suppress_filters'] ) ) {
$query->set( 'post_type', array(
'post', 'nav_menu_item', 'mvp_projects'
));
return $query;
}
}
add_filter( 'pre_get_posts', 'mvp_add_custom_types' );
``` |
288,854 | <p>I have this code:</p>
<pre><code>@font-face {
font-family: 'Miller Banner Light';
src: url('fonts/Miller-Banner-Light-01.eot'); /* IE9 Compat Modes */
src: url('fonts/Miller-Banner-Light-01.eot?#iefix') format('embedded-opentype'), /* IE6-IE8 */
url('fonts/Miller-Banner-Light-01.woff') format('woff'), /* Pretty Modern Browsers */
url('fonts/Miller-Banner-Light-01.ttf') format('truetype') /* Safari, Android, iOS */
}
</code></pre>
<p>Which in theory allows to add these fonts to my theme, unfortunately, simply creating the <code>fonts</code> folder and putting in the files doesn't work.</p>
<p>I read about having to create a child-theme but is that the only way?</p>
| [
{
"answer_id": 288837,
"author": "WhirledPress",
"author_id": 133443,
"author_profile": "https://wordpress.stackexchange.com/users/133443",
"pm_score": 1,
"selected": false,
"text": "<p>I'm not entirely sure, but it looks like you need another conditional in your filter. Right now, it filters all content looking for category, tag or date that don't have the nav_menu_item, mvp_projecvts query variable set for post types. Perhaps you could add a filter to check if some variable is set and only filter if the variable exists.</p>\n\n<p>$archive_ok= true;\n then in your filter:\nif ($archive_ok) { do stuff }\n$archive_ok=false;</p>\n\n<p>It's a clunky solution and I am sure there are better answers, but it might work in a pinch.</p>\n"
},
{
"answer_id": 288926,
"author": "worldwildwebdev",
"author_id": 48915,
"author_profile": "https://wordpress.stackexchange.com/users/48915",
"pm_score": 1,
"selected": true,
"text": "<p>I got this sorted, by adding additional contional statement and wrapped OR statements in brackets: </p>\n\n<pre><code>function mvp_add_custom_types( $query ) {\n if( ( is_category() || is_tag() || is_date() ) && $query->is_main_query() && empty( $query->query_vars['suppress_filters'] ) ) {\n $query->set( 'post_type', array(\n 'post', 'nav_menu_item', 'mvp_projects'\n ));\n return $query;\n }\n}\nadd_filter( 'pre_get_posts', 'mvp_add_custom_types' );\n</code></pre>\n"
}
]
| 2017/12/18 | [
"https://wordpress.stackexchange.com/questions/288854",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/133461/"
]
| I have this code:
```
@font-face {
font-family: 'Miller Banner Light';
src: url('fonts/Miller-Banner-Light-01.eot'); /* IE9 Compat Modes */
src: url('fonts/Miller-Banner-Light-01.eot?#iefix') format('embedded-opentype'), /* IE6-IE8 */
url('fonts/Miller-Banner-Light-01.woff') format('woff'), /* Pretty Modern Browsers */
url('fonts/Miller-Banner-Light-01.ttf') format('truetype') /* Safari, Android, iOS */
}
```
Which in theory allows to add these fonts to my theme, unfortunately, simply creating the `fonts` folder and putting in the files doesn't work.
I read about having to create a child-theme but is that the only way? | I got this sorted, by adding additional contional statement and wrapped OR statements in brackets:
```
function mvp_add_custom_types( $query ) {
if( ( is_category() || is_tag() || is_date() ) && $query->is_main_query() && empty( $query->query_vars['suppress_filters'] ) ) {
$query->set( 'post_type', array(
'post', 'nav_menu_item', 'mvp_projects'
));
return $query;
}
}
add_filter( 'pre_get_posts', 'mvp_add_custom_types' );
``` |
288,868 | <p>I'm trying to disable author's link when author's name is displayed. I don't want anything that links to the author archive. Just text without <code><a href></code>.</p>
<p>What template or file should I edit? I tried the theme template but couldn't find anything, maybe it's something related to the wp files </p>
| [
{
"answer_id": 288880,
"author": "Antonio",
"author_id": 78763,
"author_profile": "https://wordpress.stackexchange.com/users/78763",
"pm_score": 3,
"selected": true,
"text": "<p>You have actually two problems to solve here:</p>\n\n<ul>\n<li><p>The first one is to remove the HTML link, which you are trying to achieve right now. As you read in the comments, it depends on your theme. You could find it looking for the exact HTML displayed around the author name (CSS classes etc), and then seeking for it in the files of the theme (including the WordPress folder perhaps) with an editor.</p></li>\n<li><p>The second issue is less evident but probably more important: you have to actual remove that page. If you just remove the links from your template, the pages will be always visible reaching the URL <code>http://yousite.com/author/username/</code>.</p>\n\n<p>Getting inspiration by the way SEO Yoast does, you can disable the author archive page with a code like this:</p>\n\n<pre><code>function disable_author_page() {\n global $wp_query;\n\n // If an author page is requested, redirects to the home page\n if ( $wp_query->is_author ) {\n wp_safe_redirect( get_bloginfo( 'url' ), 301 );\n exit;\n }\n\n}\nadd_action( 'wp', 'disable_author_page' );\n</code></pre></li>\n</ul>\n"
},
{
"answer_id": 382265,
"author": "Deewinc",
"author_id": 180230,
"author_profile": "https://wordpress.stackexchange.com/users/180230",
"pm_score": 0,
"selected": false,
"text": "<p>Use developer tools on your browser to check for the author handler it could be <code>.author</code> or <code>.author-name</code> or .<code>author-title</code> and so forth.</p>\n<p>Then in Appearance >>> Customizations >>> Add Custom CSS do the following</p>\n<ol>\n<li><p>Add the author handler</p>\n</li>\n<li><p>Add the CSS parameter: <code>pointer-events: none</code> (This one will disable author link on posts/pages)</p>\n<p><strong>.author-title {\npointer-events: none;\n}</strong></p>\n</li>\n</ol>\n"
}
]
| 2017/12/18 | [
"https://wordpress.stackexchange.com/questions/288868",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/89820/"
]
| I'm trying to disable author's link when author's name is displayed. I don't want anything that links to the author archive. Just text without `<a href>`.
What template or file should I edit? I tried the theme template but couldn't find anything, maybe it's something related to the wp files | You have actually two problems to solve here:
* The first one is to remove the HTML link, which you are trying to achieve right now. As you read in the comments, it depends on your theme. You could find it looking for the exact HTML displayed around the author name (CSS classes etc), and then seeking for it in the files of the theme (including the WordPress folder perhaps) with an editor.
* The second issue is less evident but probably more important: you have to actual remove that page. If you just remove the links from your template, the pages will be always visible reaching the URL `http://yousite.com/author/username/`.
Getting inspiration by the way SEO Yoast does, you can disable the author archive page with a code like this:
```
function disable_author_page() {
global $wp_query;
// If an author page is requested, redirects to the home page
if ( $wp_query->is_author ) {
wp_safe_redirect( get_bloginfo( 'url' ), 301 );
exit;
}
}
add_action( 'wp', 'disable_author_page' );
``` |
288,995 | <p>Using pure PHP code inside WordPress I am having trouble on getting the <code>glob()</code> work to generate image source.</p>
<pre><code><div class="carousel-inner" role="listbox" style="height=600px; width=1000px;">
<?php
$directory = "http://geocaa.com/wp-content/themes/Booting/img/services/";
$images = glob($directory . "*.png");
foreach($images as $image)
{
echo '<div class="dynamic item">';
echo ' <img src="'.$image.'" alt="...">';
echo ' </div>';
}
?>
</div>
</code></pre>
<p>As you can see I tried to hardcoded the <code>$directory</code> as <code>"http://geocaa.com/wp-content/themes/Booting/img/services/";</code> and also I already investigate on these two Post<a href="https://stackoverflow.com/questions/19295175/wordpress-php-glob-not-working"> [Post 1</a> & <a href="https://stackoverflow.com/questions/42030975/wordpress-using-glob-returns-an-empty-array">Post 2</a> ] regarding the same issues but the solutions there still not working for me!</p>
<p>The <code>get_theme_root()</code> retuns nothing but the <code>get_template_directory()</code> is returning something which is more like</p>
<pre><code>$images = glob(get_template_directory().$directory . "*.png");
</code></pre>
<blockquote>
<p>/home/vcbb/public_html/wp-content/themes/geocaa/img/services/img.png</p>
</blockquote>
<p>and useless for image src</p>
<p>I also tried <code>get_template_directory_uri()</code> but still getting empty array</p>
| [
{
"answer_id": 288996,
"author": "Elex",
"author_id": 113687,
"author_profile": "https://wordpress.stackexchange.com/users/113687",
"pm_score": 0,
"selected": false,
"text": "<p>I think you just have to try <code>get_stylesheet_directory()</code>.</p>\n\n<pre><code>$images = glob(get_stylesheet_directory().\"/img/services/*.png\");\n</code></pre>\n\n<p>You're using <code>glob</code> on an URL, not a path actually.</p>\n"
},
{
"answer_id": 288999,
"author": "gmazzap",
"author_id": 35541,
"author_profile": "https://wordpress.stackexchange.com/users/35541",
"pm_score": 4,
"selected": true,
"text": "<p>You should use <em>paths</em> with <code>glob</code>, not <em>URLs</em>.</p>\n\n<p>But <code>src</code> attributes needs URLs.</p>\n\n<p>So something like this should work:</p>\n\n<pre><code>$base_dir = trailingslashit(get_template_directory());\n$dir = 'img/services/';\n$images = glob($base_dir.$dir.'*.png');\n\nforeach($images as $image) {\n $url = get_theme_file_uri($dir.basename($image));\n printf('<div class=\"dynamic item\"><img src=\"%s\" alt=\"\"></div>', esc_url($url));\n}\n</code></pre>\n\n<p>Where I make use of:</p>\n\n<ul>\n<li><a href=\"https://developer.wordpress.org/reference/functions/get_template_directory/\" rel=\"noreferrer\"><code>get_template_directory</code></a> To obtain the root path of (parent) theme</li>\n<li><a href=\"http://php.net/manual/en/function.basename.php\" rel=\"noreferrer\"><code>basename</code></a> to obtain just the <em>file name</em> of the current image file path</li>\n<li><a href=\"https://developer.wordpress.org/reference/functions/get_theme_file_uri/\" rel=\"noreferrer\"><code>get_theme_file_uri</code></a> to obtain the full URL of the image, in a child-theme friendly way: if the image is found in child theme it will be used from there, otherwise will be used from parent theme.</li>\n</ul>\n"
}
]
| 2017/12/19 | [
"https://wordpress.stackexchange.com/questions/288995",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/35444/"
]
| Using pure PHP code inside WordPress I am having trouble on getting the `glob()` work to generate image source.
```
<div class="carousel-inner" role="listbox" style="height=600px; width=1000px;">
<?php
$directory = "http://geocaa.com/wp-content/themes/Booting/img/services/";
$images = glob($directory . "*.png");
foreach($images as $image)
{
echo '<div class="dynamic item">';
echo ' <img src="'.$image.'" alt="...">';
echo ' </div>';
}
?>
</div>
```
As you can see I tried to hardcoded the `$directory` as `"http://geocaa.com/wp-content/themes/Booting/img/services/";` and also I already investigate on these two Post [[Post 1](https://stackoverflow.com/questions/19295175/wordpress-php-glob-not-working) & [Post 2](https://stackoverflow.com/questions/42030975/wordpress-using-glob-returns-an-empty-array) ] regarding the same issues but the solutions there still not working for me!
The `get_theme_root()` retuns nothing but the `get_template_directory()` is returning something which is more like
```
$images = glob(get_template_directory().$directory . "*.png");
```
>
> /home/vcbb/public\_html/wp-content/themes/geocaa/img/services/img.png
>
>
>
and useless for image src
I also tried `get_template_directory_uri()` but still getting empty array | You should use *paths* with `glob`, not *URLs*.
But `src` attributes needs URLs.
So something like this should work:
```
$base_dir = trailingslashit(get_template_directory());
$dir = 'img/services/';
$images = glob($base_dir.$dir.'*.png');
foreach($images as $image) {
$url = get_theme_file_uri($dir.basename($image));
printf('<div class="dynamic item"><img src="%s" alt=""></div>', esc_url($url));
}
```
Where I make use of:
* [`get_template_directory`](https://developer.wordpress.org/reference/functions/get_template_directory/) To obtain the root path of (parent) theme
* [`basename`](http://php.net/manual/en/function.basename.php) to obtain just the *file name* of the current image file path
* [`get_theme_file_uri`](https://developer.wordpress.org/reference/functions/get_theme_file_uri/) to obtain the full URL of the image, in a child-theme friendly way: if the image is found in child theme it will be used from there, otherwise will be used from parent theme. |
288,998 | <p>I'm trying to use for the second time the hook wp_ajax to call a php method from a Class inside my js script. I did it one time with success but this time, it does not work. I don't know why.</p>
<p>Context : I do this in an addon, not in my main plugin.</p>
<p>I did all these following steps :</p>
<p><strong>Add my function in my class <em>FooClass</em></strong></p>
<pre><code>namespace Namespace\Common;
class FooClass{
public static function getItems()...
public static function getItemsByAjax() {
error_log( 'getItemsByAjax' );
$f_options = self::getItems( $_POST[ 'foo_type' ] );
$json = json_encode( $f_options );
echo $json;
wp_die();
}
}
</code></pre>
<p><strong>Init this function inside another Class called on an admin page</strong></p>
<pre><code>class OtherClass{
public function __construct(){
add_action('wp_ajax_getItemsByAjax', array( 'Namespace\Common\FooClass', 'getItemsByAjax' ) );
}
}
</code></pre>
<p><strong>Usage in my jQueryScript</strong></p>
<pre><code>jQuery( function($) {
$(document).ready( function() {
$('.my-button').click(function() {
var data = {
'action': 'getItemsByAjax',
'foo_type' : 'x'
};
$.post( ajaxurl, data, function( response ) {
var jsonObj = JSON.parse( response );
console.dir( jsonObj );
});
});
});
</code></pre>
<p>});</p>
<p><em>getItemsByAjax()</em> is never called. What could I have forgotten ? </p>
| [
{
"answer_id": 289002,
"author": "Anton Lukin",
"author_id": 126253,
"author_profile": "https://wordpress.stackexchange.com/users/126253",
"pm_score": 1,
"selected": false,
"text": "<p>Finally I've found the problem in your code.\nYou've forgotten \\ on namespace path.</p>\n\n<pre><code>class OtherClass{\n\n public function __construct(){\n add_action('wp_ajax_getItemsByAjax', array( '\\Namespace\\Common\\FooClass', 'getItemsByAjax' ) );\n }\n\n}\n</code></pre>\n\n<p>I hope it will help you.</p>\n"
},
{
"answer_id": 289116,
"author": "J.BizMai",
"author_id": 128094,
"author_profile": "https://wordpress.stackexchange.com/users/128094",
"pm_score": 1,
"selected": true,
"text": "<p>After several tests, and some help inside the comments, I detect the right problem : </p>\n\n<blockquote>\n <p>if xhr response returns 0 means that the ajax function does not be hooked.</p>\n</blockquote>\n\n<p>The solution in my case was to init my addon classes with a right hook like <a href=\"https://wordpress.stackexchange.com/questions/289112/how-to-init-an-addon-correctly-after-the-main-plugin\">here</a>.</p>\n"
}
]
| 2017/12/19 | [
"https://wordpress.stackexchange.com/questions/288998",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/128094/"
]
| I'm trying to use for the second time the hook wp\_ajax to call a php method from a Class inside my js script. I did it one time with success but this time, it does not work. I don't know why.
Context : I do this in an addon, not in my main plugin.
I did all these following steps :
**Add my function in my class *FooClass***
```
namespace Namespace\Common;
class FooClass{
public static function getItems()...
public static function getItemsByAjax() {
error_log( 'getItemsByAjax' );
$f_options = self::getItems( $_POST[ 'foo_type' ] );
$json = json_encode( $f_options );
echo $json;
wp_die();
}
}
```
**Init this function inside another Class called on an admin page**
```
class OtherClass{
public function __construct(){
add_action('wp_ajax_getItemsByAjax', array( 'Namespace\Common\FooClass', 'getItemsByAjax' ) );
}
}
```
**Usage in my jQueryScript**
```
jQuery( function($) {
$(document).ready( function() {
$('.my-button').click(function() {
var data = {
'action': 'getItemsByAjax',
'foo_type' : 'x'
};
$.post( ajaxurl, data, function( response ) {
var jsonObj = JSON.parse( response );
console.dir( jsonObj );
});
});
});
```
});
*getItemsByAjax()* is never called. What could I have forgotten ? | After several tests, and some help inside the comments, I detect the right problem :
>
> if xhr response returns 0 means that the ajax function does not be hooked.
>
>
>
The solution in my case was to init my addon classes with a right hook like [here](https://wordpress.stackexchange.com/questions/289112/how-to-init-an-addon-correctly-after-the-main-plugin). |
289,048 | <p>While there may be another or better way to do it, all I need is this last snippet to make this do exactly what I need. So, I hope anyone here can and is willing to help me get it working as I need?</p>
<p>First, in the WP back-end I created and published a blank page (using a custom template) that is a required part of this formula I concocted. </p>
<p>Each time a new page is created in the WP back-end, the blank page (the custom template php file) needs to grab and display 'object1' from that newly created page. So any time a new page is created in the WP back-end, 'object1' of that new page will be pulled into the published page. How do I achieve this? Here is the code I am working with:</p>
<pre><code><?php the_field('object1', /*code for any newly created page rather than a specific number*/ ); ?>
</code></pre>
<p>What is the code to input after 'object1', for any newly created page?</p>
<p>I learned through trial and error these don't produce the result I'm needing:</p>
<pre><code><?php the_field('object1'); ?>
</code></pre>
<p>^^ The above code resulted in getting 'object1' from the current page only, which is the blank page (custom template).</p>
<pre><code><?php the_field('object1', 3 ); ?>
</code></pre>
<p>^^ The above code resulted in getting 'object1' from the page with post id number 3 in the url.</p>
<pre><code><?php the_field('object1', $post->ID ); ?>
</code></pre>
<p>^^ The above code resulted in getting 'object1' from the current page only, which is the blank page (custom template).</p>
<p>Many thanks for any guidance given.</p>
<hr>
<p><code>$post->ID</code> calls for current page, but what is the code to call for any new page created and published in WordPress?</p>
| [
{
"answer_id": 289002,
"author": "Anton Lukin",
"author_id": 126253,
"author_profile": "https://wordpress.stackexchange.com/users/126253",
"pm_score": 1,
"selected": false,
"text": "<p>Finally I've found the problem in your code.\nYou've forgotten \\ on namespace path.</p>\n\n<pre><code>class OtherClass{\n\n public function __construct(){\n add_action('wp_ajax_getItemsByAjax', array( '\\Namespace\\Common\\FooClass', 'getItemsByAjax' ) );\n }\n\n}\n</code></pre>\n\n<p>I hope it will help you.</p>\n"
},
{
"answer_id": 289116,
"author": "J.BizMai",
"author_id": 128094,
"author_profile": "https://wordpress.stackexchange.com/users/128094",
"pm_score": 1,
"selected": true,
"text": "<p>After several tests, and some help inside the comments, I detect the right problem : </p>\n\n<blockquote>\n <p>if xhr response returns 0 means that the ajax function does not be hooked.</p>\n</blockquote>\n\n<p>The solution in my case was to init my addon classes with a right hook like <a href=\"https://wordpress.stackexchange.com/questions/289112/how-to-init-an-addon-correctly-after-the-main-plugin\">here</a>.</p>\n"
}
]
| 2017/12/20 | [
"https://wordpress.stackexchange.com/questions/289048",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/58726/"
]
| While there may be another or better way to do it, all I need is this last snippet to make this do exactly what I need. So, I hope anyone here can and is willing to help me get it working as I need?
First, in the WP back-end I created and published a blank page (using a custom template) that is a required part of this formula I concocted.
Each time a new page is created in the WP back-end, the blank page (the custom template php file) needs to grab and display 'object1' from that newly created page. So any time a new page is created in the WP back-end, 'object1' of that new page will be pulled into the published page. How do I achieve this? Here is the code I am working with:
```
<?php the_field('object1', /*code for any newly created page rather than a specific number*/ ); ?>
```
What is the code to input after 'object1', for any newly created page?
I learned through trial and error these don't produce the result I'm needing:
```
<?php the_field('object1'); ?>
```
^^ The above code resulted in getting 'object1' from the current page only, which is the blank page (custom template).
```
<?php the_field('object1', 3 ); ?>
```
^^ The above code resulted in getting 'object1' from the page with post id number 3 in the url.
```
<?php the_field('object1', $post->ID ); ?>
```
^^ The above code resulted in getting 'object1' from the current page only, which is the blank page (custom template).
Many thanks for any guidance given.
---
`$post->ID` calls for current page, but what is the code to call for any new page created and published in WordPress? | After several tests, and some help inside the comments, I detect the right problem :
>
> if xhr response returns 0 means that the ajax function does not be hooked.
>
>
>
The solution in my case was to init my addon classes with a right hook like [here](https://wordpress.stackexchange.com/questions/289112/how-to-init-an-addon-correctly-after-the-main-plugin). |
289,063 | <p>I've created some custom post-types using the Pods framework, however the the solution to my question should be the same regardless of pods. My custom types are <code>event</code>, <code>team</code>, <code>achievement</code>, <code>achievementunlock</code>. Each <code>team</code> and <code>achievement</code> belongs to an <code>event</code>, each <code>team</code> has a number of users assigned, and each user can post an <code>achievementunlock</code> and choose from a list of <code>achievements</code>.</p>
<p>I'd like to create a page which displays an overview of which achievements have been "unlocked", i.e. a user has posted an achievementunlock post for.</p>
<p>Something like this</p>
<pre><code>Event1Name
| Team1 |Team2
| Bob | Steve | Scott | Mary |
Achievement1Name | View | - | - | View |
Achievement2Name | - | View | - | View |
Achievement3Name | - | - | View | |
Total | 1 | 1 | 1 | 2 |
Team Total | 2 | 3 |
Event2Name
.....
</code></pre>
<p>I'd need to be able to iterate all objects and see their properties. I.e. An <code>achievement</code> post is posted by Bob, I need to be able to also see which <code>team</code> he belongs to, and which <code>event</code> that <code>team</code> belongs to, etc.</p>
<p>How can I fetch my objects which I can iterate over them with ease, and how do I setup such a page in wordpress? Thanks!</p>
| [
{
"answer_id": 289175,
"author": "Rajilesh Panoli",
"author_id": 68892,
"author_profile": "https://wordpress.stackexchange.com/users/68892",
"pm_score": 2,
"selected": false,
"text": "<p>It seems you are asking for a complete custom funcionality,</p>\n\n<p>To add menu, you can use this.</p>\n\n<pre><code>function wpdocs_register_my_custom_menu_page() {\n add_menu_page(\n __( 'Custom Menu Title', 'textdomain' ),\n 'custom menu',\n 'manage_options',\n 'myplugin/myplugin-admin.php',\n 'custom_callback_function',\n plugins_url( 'myplugin/images/icon.png' ),\n 6\n );\n}\nadd_action( 'admin_menu', 'wpdocs_register_my_custom_menu_page' );\n\nfunction custom_callback_function(){\n\necho 'Here is my page contents';\n\n}\n</code></pre>\n\n<p><a href=\"https://developer.wordpress.org/reference/functions/add_menu_page/\" rel=\"nofollow noreferrer\">https://developer.wordpress.org/reference/functions/add_menu_page/</a></p>\n\n<p>You can use $wpdb query class for custom functionalities</p>\n\n<p><a href=\"https://codex.wordpress.org/Class_Reference/wpdb\" rel=\"nofollow noreferrer\">https://codex.wordpress.org/Class_Reference/wpdb</a></p>\n\n<p>Hopes this will give you basic idea about this.</p>\n"
},
{
"answer_id": 292044,
"author": "jsmars",
"author_id": 133576,
"author_profile": "https://wordpress.stackexchange.com/users/133576",
"pm_score": 1,
"selected": true,
"text": "<p>Although Rahilesh pointed me in the right direction and is upvoted for that, I feel that I can provide a more complete answer now that I've got things running.</p>\n\n<p>First create a new PHP template file, create a page and connect it to that template and add the page to your menu.</p>\n\n<p>In that file you can now query the wordpress databases using the <code>$wpdb</code> object as Rajilesh suggested. You can access any of the wordpress tables. Data on each post is in posts, and anything added through the Pods framework is found in postmeta where each item is has a postID and meta_key which is set in your Pods settings. </p>\n\n<p>For example:</p>\n\n<pre><code>$posts = $wpdb->get_results(\n \" SELECT * FROM $wpdb->posts WHERE \n (post_type = 'event' OR\n post_type = 'team'\");\n</code></pre>\n\n<p>Note: This will include all posts, so it may be a good idea check include some checks to avoid trashed items and drafts in your SQL query as such:</p>\n\n<pre><code>post_status <> 'draft' AND\npost_status <> 'auto-draft' AND\npost_status <> 'trash'\netc...\n</code></pre>\n\n<p>Some basic data fields use the name directly, while relationship and media fields use a <code>_pods_</code> prefix. Relationships will be arrays which hold the ID of their partner. </p>\n\n<pre><code>$meta = $wpdb->get_results(\"SELECT * FROM $wpdb->postmeta WHERE \n meta_key = '_pods_unlocks' OR\n meta_key = 'achievement' OR\n</code></pre>\n\n<p>If your setup is a bit complex as mine was, it may be a good idea to build an object oriented approach and create objects for each of your Pods.</p>\n\n<p>Now that you've gained access to all your data, you can output it in any way you see fit with custom code such as:</p>\n\n<pre><code>usort($event->Teams, \"sortTeams\");\necho \"<h3>\";\nfor ($i = 0; $i < count($event->Teams); $i++)\n{\n $team = $event->Teams[$i];\n echo ($i + 1) . \": $team->Title ($team->Score)<br/>\";\n}\necho \"</h3>\";\n</code></pre>\n\n<p>Hopefully this helps someone along the way!</p>\n"
}
]
| 2017/12/20 | [
"https://wordpress.stackexchange.com/questions/289063",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/133576/"
]
| I've created some custom post-types using the Pods framework, however the the solution to my question should be the same regardless of pods. My custom types are `event`, `team`, `achievement`, `achievementunlock`. Each `team` and `achievement` belongs to an `event`, each `team` has a number of users assigned, and each user can post an `achievementunlock` and choose from a list of `achievements`.
I'd like to create a page which displays an overview of which achievements have been "unlocked", i.e. a user has posted an achievementunlock post for.
Something like this
```
Event1Name
| Team1 |Team2
| Bob | Steve | Scott | Mary |
Achievement1Name | View | - | - | View |
Achievement2Name | - | View | - | View |
Achievement3Name | - | - | View | |
Total | 1 | 1 | 1 | 2 |
Team Total | 2 | 3 |
Event2Name
.....
```
I'd need to be able to iterate all objects and see their properties. I.e. An `achievement` post is posted by Bob, I need to be able to also see which `team` he belongs to, and which `event` that `team` belongs to, etc.
How can I fetch my objects which I can iterate over them with ease, and how do I setup such a page in wordpress? Thanks! | Although Rahilesh pointed me in the right direction and is upvoted for that, I feel that I can provide a more complete answer now that I've got things running.
First create a new PHP template file, create a page and connect it to that template and add the page to your menu.
In that file you can now query the wordpress databases using the `$wpdb` object as Rajilesh suggested. You can access any of the wordpress tables. Data on each post is in posts, and anything added through the Pods framework is found in postmeta where each item is has a postID and meta\_key which is set in your Pods settings.
For example:
```
$posts = $wpdb->get_results(
" SELECT * FROM $wpdb->posts WHERE
(post_type = 'event' OR
post_type = 'team'");
```
Note: This will include all posts, so it may be a good idea check include some checks to avoid trashed items and drafts in your SQL query as such:
```
post_status <> 'draft' AND
post_status <> 'auto-draft' AND
post_status <> 'trash'
etc...
```
Some basic data fields use the name directly, while relationship and media fields use a `_pods_` prefix. Relationships will be arrays which hold the ID of their partner.
```
$meta = $wpdb->get_results("SELECT * FROM $wpdb->postmeta WHERE
meta_key = '_pods_unlocks' OR
meta_key = 'achievement' OR
```
If your setup is a bit complex as mine was, it may be a good idea to build an object oriented approach and create objects for each of your Pods.
Now that you've gained access to all your data, you can output it in any way you see fit with custom code such as:
```
usort($event->Teams, "sortTeams");
echo "<h3>";
for ($i = 0; $i < count($event->Teams); $i++)
{
$team = $event->Teams[$i];
echo ($i + 1) . ": $team->Title ($team->Score)<br/>";
}
echo "</h3>";
```
Hopefully this helps someone along the way! |
289,110 | <p>I'm using the Enigma theme in my webpage and I want to hide the title of some posts without using any plugins. Every tutorial I find on the internet teaches me how to do it in a incompatible way for my theme. The TAGs of the HTML and the CSS code aren't matching with the structure of mine.
So I need some help to do it.</p>
| [
{
"answer_id": 289175,
"author": "Rajilesh Panoli",
"author_id": 68892,
"author_profile": "https://wordpress.stackexchange.com/users/68892",
"pm_score": 2,
"selected": false,
"text": "<p>It seems you are asking for a complete custom funcionality,</p>\n\n<p>To add menu, you can use this.</p>\n\n<pre><code>function wpdocs_register_my_custom_menu_page() {\n add_menu_page(\n __( 'Custom Menu Title', 'textdomain' ),\n 'custom menu',\n 'manage_options',\n 'myplugin/myplugin-admin.php',\n 'custom_callback_function',\n plugins_url( 'myplugin/images/icon.png' ),\n 6\n );\n}\nadd_action( 'admin_menu', 'wpdocs_register_my_custom_menu_page' );\n\nfunction custom_callback_function(){\n\necho 'Here is my page contents';\n\n}\n</code></pre>\n\n<p><a href=\"https://developer.wordpress.org/reference/functions/add_menu_page/\" rel=\"nofollow noreferrer\">https://developer.wordpress.org/reference/functions/add_menu_page/</a></p>\n\n<p>You can use $wpdb query class for custom functionalities</p>\n\n<p><a href=\"https://codex.wordpress.org/Class_Reference/wpdb\" rel=\"nofollow noreferrer\">https://codex.wordpress.org/Class_Reference/wpdb</a></p>\n\n<p>Hopes this will give you basic idea about this.</p>\n"
},
{
"answer_id": 292044,
"author": "jsmars",
"author_id": 133576,
"author_profile": "https://wordpress.stackexchange.com/users/133576",
"pm_score": 1,
"selected": true,
"text": "<p>Although Rahilesh pointed me in the right direction and is upvoted for that, I feel that I can provide a more complete answer now that I've got things running.</p>\n\n<p>First create a new PHP template file, create a page and connect it to that template and add the page to your menu.</p>\n\n<p>In that file you can now query the wordpress databases using the <code>$wpdb</code> object as Rajilesh suggested. You can access any of the wordpress tables. Data on each post is in posts, and anything added through the Pods framework is found in postmeta where each item is has a postID and meta_key which is set in your Pods settings. </p>\n\n<p>For example:</p>\n\n<pre><code>$posts = $wpdb->get_results(\n \" SELECT * FROM $wpdb->posts WHERE \n (post_type = 'event' OR\n post_type = 'team'\");\n</code></pre>\n\n<p>Note: This will include all posts, so it may be a good idea check include some checks to avoid trashed items and drafts in your SQL query as such:</p>\n\n<pre><code>post_status <> 'draft' AND\npost_status <> 'auto-draft' AND\npost_status <> 'trash'\netc...\n</code></pre>\n\n<p>Some basic data fields use the name directly, while relationship and media fields use a <code>_pods_</code> prefix. Relationships will be arrays which hold the ID of their partner. </p>\n\n<pre><code>$meta = $wpdb->get_results(\"SELECT * FROM $wpdb->postmeta WHERE \n meta_key = '_pods_unlocks' OR\n meta_key = 'achievement' OR\n</code></pre>\n\n<p>If your setup is a bit complex as mine was, it may be a good idea to build an object oriented approach and create objects for each of your Pods.</p>\n\n<p>Now that you've gained access to all your data, you can output it in any way you see fit with custom code such as:</p>\n\n<pre><code>usort($event->Teams, \"sortTeams\");\necho \"<h3>\";\nfor ($i = 0; $i < count($event->Teams); $i++)\n{\n $team = $event->Teams[$i];\n echo ($i + 1) . \": $team->Title ($team->Score)<br/>\";\n}\necho \"</h3>\";\n</code></pre>\n\n<p>Hopefully this helps someone along the way!</p>\n"
}
]
| 2017/12/20 | [
"https://wordpress.stackexchange.com/questions/289110",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/133600/"
]
| I'm using the Enigma theme in my webpage and I want to hide the title of some posts without using any plugins. Every tutorial I find on the internet teaches me how to do it in a incompatible way for my theme. The TAGs of the HTML and the CSS code aren't matching with the structure of mine.
So I need some help to do it. | Although Rahilesh pointed me in the right direction and is upvoted for that, I feel that I can provide a more complete answer now that I've got things running.
First create a new PHP template file, create a page and connect it to that template and add the page to your menu.
In that file you can now query the wordpress databases using the `$wpdb` object as Rajilesh suggested. You can access any of the wordpress tables. Data on each post is in posts, and anything added through the Pods framework is found in postmeta where each item is has a postID and meta\_key which is set in your Pods settings.
For example:
```
$posts = $wpdb->get_results(
" SELECT * FROM $wpdb->posts WHERE
(post_type = 'event' OR
post_type = 'team'");
```
Note: This will include all posts, so it may be a good idea check include some checks to avoid trashed items and drafts in your SQL query as such:
```
post_status <> 'draft' AND
post_status <> 'auto-draft' AND
post_status <> 'trash'
etc...
```
Some basic data fields use the name directly, while relationship and media fields use a `_pods_` prefix. Relationships will be arrays which hold the ID of their partner.
```
$meta = $wpdb->get_results("SELECT * FROM $wpdb->postmeta WHERE
meta_key = '_pods_unlocks' OR
meta_key = 'achievement' OR
```
If your setup is a bit complex as mine was, it may be a good idea to build an object oriented approach and create objects for each of your Pods.
Now that you've gained access to all your data, you can output it in any way you see fit with custom code such as:
```
usort($event->Teams, "sortTeams");
echo "<h3>";
for ($i = 0; $i < count($event->Teams); $i++)
{
$team = $event->Teams[$i];
echo ($i + 1) . ": $team->Title ($team->Score)<br/>";
}
echo "</h3>";
```
Hopefully this helps someone along the way! |
289,169 | <p>I want to create an A to Z index listing of all posts from a specific custom post type.
This is the code so far:</p>
<pre><code><?php
/**
* The Template for displaying archive series.
*
* Theme: Default
*/
get_header(); ?>
<div id="content">
<?php
$paged = (get_query_var('paged')) ? get_query_var('paged') : 1;
$args = array('paged' => $paged,'posts_per_page' => -1,'post_type' => 'series_type','post_status' => 'publish','orderby' => 'title','order' => 'asc');
$fruits = new WP_Query($args);
if($fruits->have_posts()){
$current_first_letter = '';
$t = array();
$s = array();
while($fruits->have_posts()){
$fruits->the_post();
$title = get_the_title();
if(is_string($title)){
$first_letter = strtoupper($title[0]);
if($first_letter != $current_first_letter){
$t[] = $first_letter;
$current_first_letter = $first_letter;
}
}
$s[$first_letter][] = get_the_title();
}
}
$t = array_unique($t);
$tc = count($t);
$sc = count($s);
for($i=0; $i<$tc; $i++){
?>
<div>
<h4><?php echo $t[$i]; ?></h4>
<ul>
<?php
foreach($s as $key => $value){
if($key == $t[$i]){
$vc = count($value);
for($j=0; $j<$vc; $j++){
?>
<li><?php echo $value[$j]; ?></li>
<?php
}
}
}
?>
</ul>
</div>
<?php
}
if($fruits->max_num_pages > 1){ ?>
<nav class="prev-next-posts">
<div class="prev-posts-link">
<?php echo get_next_posts_link( 'Older Entries', $fruits->max_num_pages ); ?>
</div>
<div class="next-posts-link">
<?php echo get_previous_posts_link( 'Newer Entries' ); ?>
</div>
</nav>
<?php } ?>
<?php wp_reset_postdata(); ?>
</div><!-- #content -->
<?php get_footer(); ?>
</code></pre>
<p>The problem is I don't know how to make all of them as hyperlinks instead of raw text. Can anyone help me fix the code?</p>
| [
{
"answer_id": 289170,
"author": "Elex",
"author_id": 113687,
"author_profile": "https://wordpress.stackexchange.com/users/113687",
"pm_score": 4,
"selected": true,
"text": "<p>Ok, you just have to make a loop with first letter check. WordPress query will handle the <code>post_title</code> <code>ASC</code> order.</p>\n\n<p><strong>EDIT :</strong> I use get_permalink() within the loop to get URL (<a href=\"https://developer.wordpress.org/reference/functions/get_permalink/\" rel=\"noreferrer\">https://developer.wordpress.org/reference/functions/get_permalink/</a>)</p>\n\n<pre><code>$series = new WP_Query(array(\n 'posts_per_page' => -1,\n 'post_type' => 'series_type',\n 'orderby' => 'title',\n 'order' => 'asc'\n));\nif($series->have_posts())\n{\n $letter = '';\n while($series->have_posts())\n {\n $series->the_post();\n\n // Check the current letter is the same that the first of the title\n if($letter != strtoupper(get_the_title()[0]))\n {\n echo ($letter != '') ? '</ul></div>' : '';\n $letter = strtoupper(get_the_title()[0]);\n echo '<div><ul><h4>'.strtoupper(get_the_title()[0]).'</h4>'; \n }\n\n echo '<li><a href=\"'.get_permalink().'\">'.get_the_title().'</a></li>';\n }\n}\n</code></pre>\n"
},
{
"answer_id": 289179,
"author": "Marcel Bootsman",
"author_id": 60585,
"author_profile": "https://wordpress.stackexchange.com/users/60585",
"pm_score": 2,
"selected": false,
"text": "<p>Try this function, I use it to create linkable A-Z index</p>\n\n<pre><code>function nstrm_sd_do_az_loop() {\n\n global $page_slug;\n\n $paged = ( get_query_var( 'paged' ) ) ? get_query_var( 'paged' ) : 1;\n $your_query = new WP_Query( array( ... ) );\n $current = '';\n\n $nav = '<div class=\"az-navigation\"><ul>';\n $letter = get_query_var( 'letter' );\n\n if ( $your_query->have_posts() ):\n while ( $your_query->have_posts() ): $your_query->the_post();\n global $post;\n\n $firstletter = strtoupper( substr( get_the_title(), 0, 1 ) );\n\n if ( $firstletter != $current ) {\n if ( $letter == $firstletter ) {\n $class = ' class=\"current\"';\n } else {\n $class = '';\n }\n $nav .= '<li' . $class . '><a href=\"/' . $page_slug . '/' . $firstletter . '\">' . $firstletter . '</a></li>';\n $current = $firstletter;\n }\n endwhile;\n\n endif;\n\n echo $nav . '<li><a href=\"/' . $page_slug . '\">' . __( 'All', 'your-text-domain' ) . '</a></li></ul></div>';\n}\n</code></pre>\n"
}
]
| 2017/12/21 | [
"https://wordpress.stackexchange.com/questions/289169",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/100682/"
]
| I want to create an A to Z index listing of all posts from a specific custom post type.
This is the code so far:
```
<?php
/**
* The Template for displaying archive series.
*
* Theme: Default
*/
get_header(); ?>
<div id="content">
<?php
$paged = (get_query_var('paged')) ? get_query_var('paged') : 1;
$args = array('paged' => $paged,'posts_per_page' => -1,'post_type' => 'series_type','post_status' => 'publish','orderby' => 'title','order' => 'asc');
$fruits = new WP_Query($args);
if($fruits->have_posts()){
$current_first_letter = '';
$t = array();
$s = array();
while($fruits->have_posts()){
$fruits->the_post();
$title = get_the_title();
if(is_string($title)){
$first_letter = strtoupper($title[0]);
if($first_letter != $current_first_letter){
$t[] = $first_letter;
$current_first_letter = $first_letter;
}
}
$s[$first_letter][] = get_the_title();
}
}
$t = array_unique($t);
$tc = count($t);
$sc = count($s);
for($i=0; $i<$tc; $i++){
?>
<div>
<h4><?php echo $t[$i]; ?></h4>
<ul>
<?php
foreach($s as $key => $value){
if($key == $t[$i]){
$vc = count($value);
for($j=0; $j<$vc; $j++){
?>
<li><?php echo $value[$j]; ?></li>
<?php
}
}
}
?>
</ul>
</div>
<?php
}
if($fruits->max_num_pages > 1){ ?>
<nav class="prev-next-posts">
<div class="prev-posts-link">
<?php echo get_next_posts_link( 'Older Entries', $fruits->max_num_pages ); ?>
</div>
<div class="next-posts-link">
<?php echo get_previous_posts_link( 'Newer Entries' ); ?>
</div>
</nav>
<?php } ?>
<?php wp_reset_postdata(); ?>
</div><!-- #content -->
<?php get_footer(); ?>
```
The problem is I don't know how to make all of them as hyperlinks instead of raw text. Can anyone help me fix the code? | Ok, you just have to make a loop with first letter check. WordPress query will handle the `post_title` `ASC` order.
**EDIT :** I use get\_permalink() within the loop to get URL (<https://developer.wordpress.org/reference/functions/get_permalink/>)
```
$series = new WP_Query(array(
'posts_per_page' => -1,
'post_type' => 'series_type',
'orderby' => 'title',
'order' => 'asc'
));
if($series->have_posts())
{
$letter = '';
while($series->have_posts())
{
$series->the_post();
// Check the current letter is the same that the first of the title
if($letter != strtoupper(get_the_title()[0]))
{
echo ($letter != '') ? '</ul></div>' : '';
$letter = strtoupper(get_the_title()[0]);
echo '<div><ul><h4>'.strtoupper(get_the_title()[0]).'</h4>';
}
echo '<li><a href="'.get_permalink().'">'.get_the_title().'</a></li>';
}
}
``` |
289,258 | <p>I'm hoping someone can help as I have searched and cannot find an answer...</p>
<p>I am using a loop in a shortcode to display a list of related items and I'm having trouble working out the logic of selecting multiple categories in an AND parameter.</p>
<p>For example, I have a category structure like this:</p>
<pre><code>Products (id: 1)
Prod A (id: 2)
Prod B (id: 3)
Services (id: 4)
Service A (id: 5)
Service B (id: 6)
Overview (id: 7)
</code></pre>
<p>What I would like to do is show all posts that are categorised as id 7 AND specific other IDs.</p>
<p>For example:</p>
<pre><code>'category__and' => array(7,2),
AND
'category__and' => array(7,5),
</code></pre>
<p>Which would show 2 results - posts categorised as (Overview AND Prod A) AND (Overview AND Service A).</p>
<p>Everything works if I only want to show one selection (eg. Overview AND Prod A) but I can't work out how to show multiples.</p>
<p>Changing it to category__in does not work because that shows all posts categorised as Overview including Prod B and Service B, in the above example. It's also not practical to use category__not_in to exclude categories because the list is quite long and will change (unless there's a way of programmatically working out which categories to exclude?).</p>
<p>Is there a way of using multiple pairs of category__and values, or a way of coding multiple loops for WP_Query to achieve this?</p>
<p>I hope that gives you enough to go on. Thanks in advance!</p>
| [
{
"answer_id": 289239,
"author": "Gordon Smith",
"author_id": 73331,
"author_profile": "https://wordpress.stackexchange.com/users/73331",
"pm_score": 2,
"selected": false,
"text": "<p>To shorten your search the article points out that the suggested code is old and that you can now use this plug-in to define custom colors: <a href=\"https://wordpress.org/plugins/kt-tinymce-color-grid/\" rel=\"nofollow noreferrer\">Central Color Palette</a></p>\n"
},
{
"answer_id": 289241,
"author": "Brad Holmes",
"author_id": 133516,
"author_profile": "https://wordpress.stackexchange.com/users/133516",
"pm_score": 1,
"selected": false,
"text": "<p>if you are using the same color every time then add a piece of css to your site </p>\n\n<p>ie </p>\n\n<p>.keyword{color:#11c8de;}</p>\n\n<p>then span your special word with <code><span class=\"keyword\">YOUR SPECIAL WORD</span></code></p>\n\n<p>this offeres more flexibility if you want to change the color in the future all you change is your css and not every single word.</p>\n"
}
]
| 2017/12/22 | [
"https://wordpress.stackexchange.com/questions/289258",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/133687/"
]
| I'm hoping someone can help as I have searched and cannot find an answer...
I am using a loop in a shortcode to display a list of related items and I'm having trouble working out the logic of selecting multiple categories in an AND parameter.
For example, I have a category structure like this:
```
Products (id: 1)
Prod A (id: 2)
Prod B (id: 3)
Services (id: 4)
Service A (id: 5)
Service B (id: 6)
Overview (id: 7)
```
What I would like to do is show all posts that are categorised as id 7 AND specific other IDs.
For example:
```
'category__and' => array(7,2),
AND
'category__and' => array(7,5),
```
Which would show 2 results - posts categorised as (Overview AND Prod A) AND (Overview AND Service A).
Everything works if I only want to show one selection (eg. Overview AND Prod A) but I can't work out how to show multiples.
Changing it to category\_\_in does not work because that shows all posts categorised as Overview including Prod B and Service B, in the above example. It's also not practical to use category\_\_not\_in to exclude categories because the list is quite long and will change (unless there's a way of programmatically working out which categories to exclude?).
Is there a way of using multiple pairs of category\_\_and values, or a way of coding multiple loops for WP\_Query to achieve this?
I hope that gives you enough to go on. Thanks in advance! | To shorten your search the article points out that the suggested code is old and that you can now use this plug-in to define custom colors: [Central Color Palette](https://wordpress.org/plugins/kt-tinymce-color-grid/) |
289,269 | <p>I have create a custom meta key into the post table and it's value is in serialized form now when I dump the value it is giving me like this</p>
<blockquote>
<p>Array ( [0] => a:3:{s:10:"product_id";s:4:"2592";s:7:"user_id";i:41;i:0;a:1:{i:0;s:63:"a:3:{s:10:"product_id";s:4:"2592";s:7:"user_id";i:2;i:0;a:0:{}}";}} )</p>
</blockquote>
<p>I want to get user_id and product_id from it. The main idea is to hide a button for those user whose ID's are stored into this meta_key for the particular product whose ID are in this serialized array as well any idea how to do that I have tried the following code but nothing happens</p>
<pre><code>$next_in_line = get_post_meta(esc_attr($product->get_id()), '_next_in_line');
print_r($next_in_line);
$unserilize_data = unserialize($next_in_line);
print_r($unserilize_data['0']);
</code></pre>
<p>But is giving me bool(false) and when I use this function</p>
<pre><code>$next_in_line = get_post_meta(esc_attr($product->get_id()), '_next_in_line');
print_r($next_in_line);
$un_data = maybe_unserialize($next_in_line);
print_r($un_data['0']);
</code></pre>
<p>it is returning me values in the following format</p>
<blockquote>
<p>a:3:{s:10:"product_id";s:4:"2592";s:7:"user_id";i:41;i:0;a:1:{i:0;s:63:"a:3:{s:10:"product_id";s:4:"2592";s:7:"user_id";i:2;i:0;a:0:{}}";}}</p>
</blockquote>
<p>Now how can I make the condition that I have mentioned above I am blank at this point please some one help me out. Thank you in advance</p>
<p><strong>UPDATE</strong></p>
<p>I am storing data like this</p>
<pre><code>function nextInLine(){
$product_id = $_POST['product_id'];
$user_id = get_current_user_id();
$next_customer_meta = get_post_meta($product_id, '_next_in_line');
if($next_customer_meta == ''){
$meta_array = array(
'product_id' => $product_id,
'user_id' => $user_id
);
$meta_value = maybe_serialize($meta_array);
} else {
$meta_array = array(
'product_id' => $product_id,
'user_id' => $user_id
);
array_push($meta_array, $next_customer_meta);
$meta_value = maybe_serialize($meta_array);
}
var_dump($meta_value);
update_post_meta($product_id, '_next_in_line', $meta_value);
return true;
}
add_action('wp_ajax_nextInLine', 'nextInLine');
add_action('wp_ajax_nopriv_nextInLine', 'nextInLine');
</code></pre>
| [
{
"answer_id": 289264,
"author": "Jacob Peattie",
"author_id": 39152,
"author_profile": "https://wordpress.stackexchange.com/users/39152",
"pm_score": 1,
"selected": false,
"text": "<p>As stated in the <a href=\"https://make.wordpress.org/core/2017/10/13/account-security-improvements-in-wordpress-4-9/\" rel=\"nofollow noreferrer\">announcement post</a>:</p>\n\n<blockquote>\n <p>A few account security enhancements have gone into WordPress 4.9. The\n intention is to make it more difficult for an attacker to take over a\n user account or a site by changing the email address associated with\n the user or the site, and also to reduce the chance of a mistaken or\n erroneous change causing you to get locked out.</p>\n</blockquote>\n"
},
{
"answer_id": 305306,
"author": "Hasse",
"author_id": 144815,
"author_profile": "https://wordpress.stackexchange.com/users/144815",
"pm_score": 0,
"selected": false,
"text": "<p>This function doesnΒ΄t work for me. Also tried with a SMTP-plugin. DonΒ΄t get any email to the correct email I want to use as admin email. It worked to send as a test to a @gmail-address! Had the same problems on 3 other sites also.</p>\n\n<p>Changed it directly in the db instead.</p>\n"
}
]
| 2017/12/22 | [
"https://wordpress.stackexchange.com/questions/289269",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/132946/"
]
| I have create a custom meta key into the post table and it's value is in serialized form now when I dump the value it is giving me like this
>
> Array ( [0] => a:3:{s:10:"product\_id";s:4:"2592";s:7:"user\_id";i:41;i:0;a:1:{i:0;s:63:"a:3:{s:10:"product\_id";s:4:"2592";s:7:"user\_id";i:2;i:0;a:0:{}}";}} )
>
>
>
I want to get user\_id and product\_id from it. The main idea is to hide a button for those user whose ID's are stored into this meta\_key for the particular product whose ID are in this serialized array as well any idea how to do that I have tried the following code but nothing happens
```
$next_in_line = get_post_meta(esc_attr($product->get_id()), '_next_in_line');
print_r($next_in_line);
$unserilize_data = unserialize($next_in_line);
print_r($unserilize_data['0']);
```
But is giving me bool(false) and when I use this function
```
$next_in_line = get_post_meta(esc_attr($product->get_id()), '_next_in_line');
print_r($next_in_line);
$un_data = maybe_unserialize($next_in_line);
print_r($un_data['0']);
```
it is returning me values in the following format
>
> a:3:{s:10:"product\_id";s:4:"2592";s:7:"user\_id";i:41;i:0;a:1:{i:0;s:63:"a:3:{s:10:"product\_id";s:4:"2592";s:7:"user\_id";i:2;i:0;a:0:{}}";}}
>
>
>
Now how can I make the condition that I have mentioned above I am blank at this point please some one help me out. Thank you in advance
**UPDATE**
I am storing data like this
```
function nextInLine(){
$product_id = $_POST['product_id'];
$user_id = get_current_user_id();
$next_customer_meta = get_post_meta($product_id, '_next_in_line');
if($next_customer_meta == ''){
$meta_array = array(
'product_id' => $product_id,
'user_id' => $user_id
);
$meta_value = maybe_serialize($meta_array);
} else {
$meta_array = array(
'product_id' => $product_id,
'user_id' => $user_id
);
array_push($meta_array, $next_customer_meta);
$meta_value = maybe_serialize($meta_array);
}
var_dump($meta_value);
update_post_meta($product_id, '_next_in_line', $meta_value);
return true;
}
add_action('wp_ajax_nextInLine', 'nextInLine');
add_action('wp_ajax_nopriv_nextInLine', 'nextInLine');
``` | As stated in the [announcement post](https://make.wordpress.org/core/2017/10/13/account-security-improvements-in-wordpress-4-9/):
>
> A few account security enhancements have gone into WordPress 4.9. The
> intention is to make it more difficult for an attacker to take over a
> user account or a site by changing the email address associated with
> the user or the site, and also to reduce the chance of a mistaken or
> erroneous change causing you to get locked out.
>
>
> |
289,281 | <p>I'm working on a relationship filter using <a href="https://www.advancedcustomfields.com/resources/acf-fields-relationship-query/" rel="nofollow noreferrer">this documentary</a>.</p>
<p>I made so far but can't make my return value. Normally in a custom Template I just echo it, but it's different in a function I think.</p>
<pre><code>function soup_filter( $args, $field, $post_id ) {
$args = array('post_type' => 'menu');
$query = new WP_Query( $args );
$soups = get_field('soups');
foreach ($soups as $soup) {
//return value stored here in $soup
}
// return
return $args;
}
add_filter('acf/fields/relationship/query/key=field_59f736725fe5d', 'soup_filter', 10, 3);
</code></pre>
| [
{
"answer_id": 289264,
"author": "Jacob Peattie",
"author_id": 39152,
"author_profile": "https://wordpress.stackexchange.com/users/39152",
"pm_score": 1,
"selected": false,
"text": "<p>As stated in the <a href=\"https://make.wordpress.org/core/2017/10/13/account-security-improvements-in-wordpress-4-9/\" rel=\"nofollow noreferrer\">announcement post</a>:</p>\n\n<blockquote>\n <p>A few account security enhancements have gone into WordPress 4.9. The\n intention is to make it more difficult for an attacker to take over a\n user account or a site by changing the email address associated with\n the user or the site, and also to reduce the chance of a mistaken or\n erroneous change causing you to get locked out.</p>\n</blockquote>\n"
},
{
"answer_id": 305306,
"author": "Hasse",
"author_id": 144815,
"author_profile": "https://wordpress.stackexchange.com/users/144815",
"pm_score": 0,
"selected": false,
"text": "<p>This function doesnΒ΄t work for me. Also tried with a SMTP-plugin. DonΒ΄t get any email to the correct email I want to use as admin email. It worked to send as a test to a @gmail-address! Had the same problems on 3 other sites also.</p>\n\n<p>Changed it directly in the db instead.</p>\n"
}
]
| 2017/12/22 | [
"https://wordpress.stackexchange.com/questions/289281",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/133469/"
]
| I'm working on a relationship filter using [this documentary](https://www.advancedcustomfields.com/resources/acf-fields-relationship-query/).
I made so far but can't make my return value. Normally in a custom Template I just echo it, but it's different in a function I think.
```
function soup_filter( $args, $field, $post_id ) {
$args = array('post_type' => 'menu');
$query = new WP_Query( $args );
$soups = get_field('soups');
foreach ($soups as $soup) {
//return value stored here in $soup
}
// return
return $args;
}
add_filter('acf/fields/relationship/query/key=field_59f736725fe5d', 'soup_filter', 10, 3);
``` | As stated in the [announcement post](https://make.wordpress.org/core/2017/10/13/account-security-improvements-in-wordpress-4-9/):
>
> A few account security enhancements have gone into WordPress 4.9. The
> intention is to make it more difficult for an attacker to take over a
> user account or a site by changing the email address associated with
> the user or the site, and also to reduce the chance of a mistaken or
> erroneous change causing you to get locked out.
>
>
> |
289,287 | <p><code>ABSPATH</code> outputs like <code>C/:docs/http_root/public_html/</code> or <code>/home/userXXXXX/public_html</code> (or etc, depending on server).</p>
<p>However, I want to get the file location according to its relative path from <code>ABSPATH</code>. How to achieve that?</p>
<p>i.e. I want to get from file:</p>
<pre><code>C/:docs/http_root/public_html/some_folder/file.php
---->
/some_folder/file.php
</code></pre>
<p>P.S. </p>
<p>1) <code>request_uri</code> and <code>php_self</code> wont help in this case.</p>
<p>2) Maybe it's surprising but even this doesn't help on all servers: <code>str_replace(ABSPATH, '', __DIR__)</code> </p>
| [
{
"answer_id": 289264,
"author": "Jacob Peattie",
"author_id": 39152,
"author_profile": "https://wordpress.stackexchange.com/users/39152",
"pm_score": 1,
"selected": false,
"text": "<p>As stated in the <a href=\"https://make.wordpress.org/core/2017/10/13/account-security-improvements-in-wordpress-4-9/\" rel=\"nofollow noreferrer\">announcement post</a>:</p>\n\n<blockquote>\n <p>A few account security enhancements have gone into WordPress 4.9. The\n intention is to make it more difficult for an attacker to take over a\n user account or a site by changing the email address associated with\n the user or the site, and also to reduce the chance of a mistaken or\n erroneous change causing you to get locked out.</p>\n</blockquote>\n"
},
{
"answer_id": 305306,
"author": "Hasse",
"author_id": 144815,
"author_profile": "https://wordpress.stackexchange.com/users/144815",
"pm_score": 0,
"selected": false,
"text": "<p>This function doesnΒ΄t work for me. Also tried with a SMTP-plugin. DonΒ΄t get any email to the correct email I want to use as admin email. It worked to send as a test to a @gmail-address! Had the same problems on 3 other sites also.</p>\n\n<p>Changed it directly in the db instead.</p>\n"
}
]
| 2017/12/22 | [
"https://wordpress.stackexchange.com/questions/289287",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/33667/"
]
| `ABSPATH` outputs like `C/:docs/http_root/public_html/` or `/home/userXXXXX/public_html` (or etc, depending on server).
However, I want to get the file location according to its relative path from `ABSPATH`. How to achieve that?
i.e. I want to get from file:
```
C/:docs/http_root/public_html/some_folder/file.php
---->
/some_folder/file.php
```
P.S.
1) `request_uri` and `php_self` wont help in this case.
2) Maybe it's surprising but even this doesn't help on all servers: `str_replace(ABSPATH, '', __DIR__)` | As stated in the [announcement post](https://make.wordpress.org/core/2017/10/13/account-security-improvements-in-wordpress-4-9/):
>
> A few account security enhancements have gone into WordPress 4.9. The
> intention is to make it more difficult for an attacker to take over a
> user account or a site by changing the email address associated with
> the user or the site, and also to reduce the chance of a mistaken or
> erroneous change causing you to get locked out.
>
>
> |
289,293 | <p>I have manually created a role called "event-planner". I've assigned some capabilities to it and it works as expected. However, if I later set one of the capabilities from true to false (or vice versa), changes won't reflect on WordPress. I think this is related to WordPress not updating the capabilities because if I delete the role and then add the code again, then it will work.</p>
<p>Is there a way to "tell" WordPress to update my role capabilities once they were set?</p>
<p>Here is my code:</p>
<pre class="lang-php prettyprint-override"><code>$result = add_role('event-planner', __('Event Planner'),
array(
'read' => true,
'delete_others_events' => false,
'delete_private_events' => true,
'delete_published_events' => true,
'delete_events' => true,
'edit_others_events' => false,
'edit_private_events' => true,
'edit_published_events' => true,
'edit_events' => true,
'publish_events' => true,
'read_private_events' => true
)
);
</code></pre>
| [
{
"answer_id": 289294,
"author": "HU is Sebastian",
"author_id": 56587,
"author_profile": "https://wordpress.stackexchange.com/users/56587",
"pm_score": 2,
"selected": false,
"text": "<p>You can use the function <a href=\"https://codex.wordpress.org/Function_Reference/add_cap\" rel=\"nofollow noreferrer\">add_cap</a></p>\n\n<p>maybe like this:</p>\n\n<pre><code>function add_my_capabilities($cap){\n $role = get_role('event-planner');\n $role->add_cap($cap);\n}\n\nadd_my_capabilities('edit_others_events');\n</code></pre>\n"
},
{
"answer_id": 289295,
"author": "Jacob Peattie",
"author_id": 39152,
"author_profile": "https://wordpress.stackexchange.com/users/39152",
"pm_score": 3,
"selected": false,
"text": "<p><code>add_role()</code> will not do anything if the role already exists, so it can't be used to modify capabilities. To modify capabilities use the <code>add_cap()</code> and <code>remove_cap()</code> method of the <code>WP_Role</code> object. You can get a <code>WP_Role</code> for your role using <code>get_role()</code>:</p>\n\n<pre><code>$role = get_role( 'event-planner' );\n$role->add_cap( 'edit_others_events' );\n</code></pre>\n\n<p>Here's the thing though, roles are stored in the database, so adding roles or capabilities are things that shouldn't be happening on every page load. If you want to modify an existing role, you'll need to do it just once. So that means you'll need to do it on theme or plugin activation, or when saving an options page. The same goes for creating the role to begin with.</p>\n\n<p>Given that, if this is just a plugin/role that exists on just on your site, you're probably better of just using a plugin like <a href=\"https://wordpress.org/plugins/user-role-editor/\" rel=\"noreferrer\">User Role Editor</a>.</p>\n\n<p>If it's a distributed plugin, you could do it in a hook that loads on every page, but just check an option to see if the update has already been done:</p>\n\n<pre><code>function wpse_289293_update_role() {\n // Get current version of user role.\n $version = get_option( 'wpse_289293_roles_version' )\n\n // Define version number that represents this change.\n $new_version = 2;\n\n // If current version is lower than new version.\n if ( $version < $new_version ) {\n // Update the role.\n $role = get_role( 'event-planner' );\n $role->add_cap( 'edit_others_events' );\n\n // Update db to indicate role has been updated.\n update_option( 'wpse_289293_db_version', $new_version );\n }\n}\nadd_action( 'plugins_loaded', 'wpse_289293_update_role' );\n</code></pre>\n\n<p>Because the role's capabilities aren't being forced on every page reload this also has the advantage of allowing users to use a user role editor plugin to modify the capabilities themselves. If <code>add_cap()</code> was being run on every page load it would overwrite any changes they would make.</p>\n"
},
{
"answer_id": 379876,
"author": "Chandan Kumar Thakur",
"author_id": 88637,
"author_profile": "https://wordpress.stackexchange.com/users/88637",
"pm_score": 1,
"selected": false,
"text": "<p>This will save your time updating a role:</p>\n<pre><code>$wp_roles = new WP_Roles();\n$wp_roles->remove_role("volunteer");\nadd_role( 'volunteer', 'Volunteer', array(\n 'read' => true\n ) );\n</code></pre>\n"
}
]
| 2017/12/22 | [
"https://wordpress.stackexchange.com/questions/289293",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/21245/"
]
| I have manually created a role called "event-planner". I've assigned some capabilities to it and it works as expected. However, if I later set one of the capabilities from true to false (or vice versa), changes won't reflect on WordPress. I think this is related to WordPress not updating the capabilities because if I delete the role and then add the code again, then it will work.
Is there a way to "tell" WordPress to update my role capabilities once they were set?
Here is my code:
```php
$result = add_role('event-planner', __('Event Planner'),
array(
'read' => true,
'delete_others_events' => false,
'delete_private_events' => true,
'delete_published_events' => true,
'delete_events' => true,
'edit_others_events' => false,
'edit_private_events' => true,
'edit_published_events' => true,
'edit_events' => true,
'publish_events' => true,
'read_private_events' => true
)
);
``` | `add_role()` will not do anything if the role already exists, so it can't be used to modify capabilities. To modify capabilities use the `add_cap()` and `remove_cap()` method of the `WP_Role` object. You can get a `WP_Role` for your role using `get_role()`:
```
$role = get_role( 'event-planner' );
$role->add_cap( 'edit_others_events' );
```
Here's the thing though, roles are stored in the database, so adding roles or capabilities are things that shouldn't be happening on every page load. If you want to modify an existing role, you'll need to do it just once. So that means you'll need to do it on theme or plugin activation, or when saving an options page. The same goes for creating the role to begin with.
Given that, if this is just a plugin/role that exists on just on your site, you're probably better of just using a plugin like [User Role Editor](https://wordpress.org/plugins/user-role-editor/).
If it's a distributed plugin, you could do it in a hook that loads on every page, but just check an option to see if the update has already been done:
```
function wpse_289293_update_role() {
// Get current version of user role.
$version = get_option( 'wpse_289293_roles_version' )
// Define version number that represents this change.
$new_version = 2;
// If current version is lower than new version.
if ( $version < $new_version ) {
// Update the role.
$role = get_role( 'event-planner' );
$role->add_cap( 'edit_others_events' );
// Update db to indicate role has been updated.
update_option( 'wpse_289293_db_version', $new_version );
}
}
add_action( 'plugins_loaded', 'wpse_289293_update_role' );
```
Because the role's capabilities aren't being forced on every page reload this also has the advantage of allowing users to use a user role editor plugin to modify the capabilities themselves. If `add_cap()` was being run on every page load it would overwrite any changes they would make. |
289,307 | <p>I'm using <a href="https://www.themepunch.com/essgrid-doc/essential-grid-documentation/" rel="nofollow noreferrer">Essential Grid</a> plugin to create a custom meta field for posts. I've created a simple image field. The plan is to add the URL of the featured image. Problem is I'm not sure how to get the physical URL.</p>
<p>For instance, I'm trying to get <code>/mysite.com/wp-contents/uploads/my-image.jpg</code>.</p>
<p>What's the best and fastest way to get the URL?</p>
| [
{
"answer_id": 289309,
"author": "Johansson",
"author_id": 94498,
"author_profile": "https://wordpress.stackexchange.com/users/94498",
"pm_score": 0,
"selected": false,
"text": "<p>If you are trying to retrieve the post's featured image URI, you can use the <a href=\"https://developer.wordpress.org/reference/functions/get_the_post_thumbnail_url/\" rel=\"nofollow noreferrer\"><code>get_the_post_thumbnail_url()</code></a>:</p>\n\n<pre><code>$uri = get_the_post_thumbnail_url( $post_id, $size );\n</code></pre>\n"
},
{
"answer_id": 289310,
"author": "Tom J Nowell",
"author_id": 736,
"author_profile": "https://wordpress.stackexchange.com/users/736",
"pm_score": 1,
"selected": false,
"text": "<p>The function to use would be:</p>\n\n<pre><code>$url = get_the_post_thumbnail_url();\n</code></pre>\n\n<p>However, that's not the most helpful for you right now, so we have a meta field with placeholders that you need to swap out for URLs before outputting.</p>\n\n<p>breaking that down we get these smaller steps:</p>\n\n<pre><code>// grab the field\n// grab the URL\n// swap the placeholder out for the URL\n// output the field\n</code></pre>\n\n<p>So lets do each individual bit:</p>\n\n<pre><code>// grab the field\n$meta = get_post_meta( ....\n\n// grab the URL\n$thumb_url = get_the_post_thumbnail_url();\n\n// swap the thumbnail placeholder out for the URL\n$meta = str_replace( '%thumbnail%', $thumb_url, $meta );\n\n// output the meta field\necho wp_kses_post( $meta );\n</code></pre>\n\n<p>Notice the <code>wp_kses_post</code> which strips out dangerous HTML while letting you keep <code>img</code> tags etc</p>\n"
}
]
| 2017/12/22 | [
"https://wordpress.stackexchange.com/questions/289307",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/60386/"
]
| I'm using [Essential Grid](https://www.themepunch.com/essgrid-doc/essential-grid-documentation/) plugin to create a custom meta field for posts. I've created a simple image field. The plan is to add the URL of the featured image. Problem is I'm not sure how to get the physical URL.
For instance, I'm trying to get `/mysite.com/wp-contents/uploads/my-image.jpg`.
What's the best and fastest way to get the URL? | The function to use would be:
```
$url = get_the_post_thumbnail_url();
```
However, that's not the most helpful for you right now, so we have a meta field with placeholders that you need to swap out for URLs before outputting.
breaking that down we get these smaller steps:
```
// grab the field
// grab the URL
// swap the placeholder out for the URL
// output the field
```
So lets do each individual bit:
```
// grab the field
$meta = get_post_meta( ....
// grab the URL
$thumb_url = get_the_post_thumbnail_url();
// swap the thumbnail placeholder out for the URL
$meta = str_replace( '%thumbnail%', $thumb_url, $meta );
// output the meta field
echo wp_kses_post( $meta );
```
Notice the `wp_kses_post` which strips out dangerous HTML while letting you keep `img` tags etc |
289,321 | <p>I tried to make a child theme to change some colors. I used this <a href="https://codex.wordpress.org/Child_Themes" rel="nofollow noreferrer">https://codex.wordpress.org/Child_Themes</a> tutorial, but I still can't get this done. The problem is that I am not able to override some styles, because my stylesheet called "bootstrap.css" is not getting loaded.
My functions.php file looks like this</p>
<pre><code><?php
function my_theme_enqueue_styles() {
$parent_style = 'maxstore_theme_stylesheets'; // This is 'twentyfifteen-style' for the Twenty Fifteen theme.
wp_enqueue_style( $parent_style, get_template_directory_uri() . '/style.css' );
wp_enqueue_style( $parent_style, get_template_directory_uri() . '/css/bootstrap.css' );
wp_enqueue_style( 'child-style', get_template_directory_uri() . '/style.css', array( $parent_style ), wp_get_theme()->get('Version'));
wp_enqueue_style( 'child-style', get_template_directory_uri() . '/css/bootstrap.css', array( $parent_style ), wp_get_theme()->get('Version'));
}
add_action( 'wp_enqueue_scripts', 'my_theme_enqueue_styles' );
?>
</code></pre>
<p>These are the files that are getting loaded
<a href="https://i.stack.imgur.com/BZaTo.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/BZaTo.png" alt="enter image description here"></a></p>
<p><strong>EDIT 1:</strong>
I'm now using this code and it still isn't working</p>
<pre><code><?php
function my_theme_enqueue_styles() {
$parent_style = 'maxstore_theme_stylesheets'; // This is 'twentyfifteen-style' for the Twenty Fifteen theme.
wp_enqueue_style( $parent_style, get_template_directory_uri() . '/style.css' );
wp_enqueue_style( $parent_style, get_template_directory_uri() . '/css/bootstrap.css' );
wp_enqueue_style( 'child-style', get_stylesheet_directory_uri() . '/style.css', array( $parent_style ), wp_get_theme()->get('Version'));
wp_enqueue_style( 'child-style', get_stylesheet_directory_uri() . '/css/bootstrap.css', array( $parent_style ), wp_get_theme()->get('Version'));
}
add_action( 'wp_enqueue_scripts', 'my_theme_enqueue_styles' );
?>
</code></pre>
<p><strong>EDIT 2:</strong>
My bootstrap stylesheet is getting loaded, but for some reason my website is still using another version of it. As you can see it uses 3 times the same styles and the one that is really used is version 3.3.4. and I want to use the one with the blue color which is version 1.0.2
<a href="https://i.stack.imgur.com/SkvA9.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/SkvA9.png" alt="enter image description here"></a>
Version 3.3.4 in the picture and I want to use the bootstrap version 1.0.2.
<a href="https://i.stack.imgur.com/9ygYt.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/9ygYt.png" alt="enter image description here"></a>
<strong>EDIT 3:</strong>
Code from functions.php that I am using at the moment</p>
<pre><code><?php
function my_theme_enqueue_styles() {
$parent_styles = array('maxstore_theme_style', 'maxstore_theme_bootstrap');
// This is 'twentyfifteen-style' for the Twenty Fifteen theme.
wp_enqueue_style( $parent_styles[0], get_template_directory_uri() .
'/style.css' );
wp_enqueue_style( $parent_styles[1], get_template_directory_uri() .
'/css/bootstrap.css' );
wp_enqueue_style( 'child-style', get_stylesheet_directory_uri() .
'/style.css', $parent_styles, wp_get_theme()->get('Version'));
wp_enqueue_style( 'child-bootstrap', get_stylesheet_directory_uri() .
'/css/bootstrap.css', $parent_styles, wp_get_theme()->get('Version'));
}
add_action( 'wp_enqueue_scripts', 'my_theme_enqueue_styles' );
?>
</code></pre>
| [
{
"answer_id": 289322,
"author": "Tom J Nowell",
"author_id": 736,
"author_profile": "https://wordpress.stackexchange.com/users/736",
"pm_score": 3,
"selected": true,
"text": "<h2>Parent vs Child Themes</h2>\n\n<p><code>get_template_directory_uri</code> always refers to the parent theme you can verify this as you always should when things don't load as expected by looking in the console in the browsers dev tools. These would show 404 errors for the CSS files, in the wrong folder.</p>\n\n<p>Instead, use <code>get_stylesheet_directory_uri</code>, the <code>stylesheet</code> family of functions always refer to the current active theme</p>\n\n<h2>Duplicated Names</h2>\n\n<pre><code>wp_enqueue_style( 'child-style', get_stylesheet_directory_uri() . '/style.css', array( $parent_style ), wp_get_theme()->get('Version'));\nwp_enqueue_style( 'child-style', get_stylesheet_directory_uri() . '/css/bootstrap.css', array( $parent_style ), wp_get_theme()->get('Version'));\n</code></pre>\n\n<p>You can't call 2 stylesheets the same thing and expect it to work, which is what you've done with all 4 of your stylesheets</p>\n\n<p>Also notice that you've loaded <code>bootstrap.css</code> from both themes</p>\n"
},
{
"answer_id": 289368,
"author": "Landing on Jupiter",
"author_id": 74534,
"author_profile": "https://wordpress.stackexchange.com/users/74534",
"pm_score": 2,
"selected": false,
"text": "<p>Each enqueue request needs a unique handle (or name), which is the first argument in the <a href=\"https://developer.wordpress.org/reference/functions/wp_enqueue_style/\" rel=\"nofollow noreferrer\">wp_enqueue_style hook</a>. Since your first two and last two commands are given the same handle, it's probably only loading two of the four. </p>\n\n<p>Try this. I followed your model of declaring a variable for the Parent Style handle. I've replaced $parent_style with an array containing two unique handles. Note that this means the dependency statement no longer needs an array, since the variable we're using is already one, as reflected in my code.</p>\n\n<pre><code><?php\nfunction my_theme_enqueue_styles() {\n $parent_styles = array( 'maxstore_theme_style', 'maxstore_theme_bootstrap' );\n wp_enqueue_style( $parent_styles[0], get_template_directory_uri() . '/style.css' );\n wp_enqueue_style( $parent_styles[1], get_template_directory_uri() . '/css/bootstrap.css' );\n wp_enqueue_style( 'child-style', get_stylesheet_directory_uri() . '/style.css', $parent_styles, wp_get_theme()->get('Version'));\n wp_enqueue_style( 'child-bootstrap', get_stylesheet_directory_uri() . '/css/bootstrap.css', $parent_styles, wp_get_theme()->get('Version'));\n}\nadd_action( 'wp_enqueue_scripts', 'my_theme_enqueue_styles' );\n?>\n</code></pre>\n"
}
]
| 2017/12/22 | [
"https://wordpress.stackexchange.com/questions/289321",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/133727/"
]
| I tried to make a child theme to change some colors. I used this <https://codex.wordpress.org/Child_Themes> tutorial, but I still can't get this done. The problem is that I am not able to override some styles, because my stylesheet called "bootstrap.css" is not getting loaded.
My functions.php file looks like this
```
<?php
function my_theme_enqueue_styles() {
$parent_style = 'maxstore_theme_stylesheets'; // This is 'twentyfifteen-style' for the Twenty Fifteen theme.
wp_enqueue_style( $parent_style, get_template_directory_uri() . '/style.css' );
wp_enqueue_style( $parent_style, get_template_directory_uri() . '/css/bootstrap.css' );
wp_enqueue_style( 'child-style', get_template_directory_uri() . '/style.css', array( $parent_style ), wp_get_theme()->get('Version'));
wp_enqueue_style( 'child-style', get_template_directory_uri() . '/css/bootstrap.css', array( $parent_style ), wp_get_theme()->get('Version'));
}
add_action( 'wp_enqueue_scripts', 'my_theme_enqueue_styles' );
?>
```
These are the files that are getting loaded
[](https://i.stack.imgur.com/BZaTo.png)
**EDIT 1:**
I'm now using this code and it still isn't working
```
<?php
function my_theme_enqueue_styles() {
$parent_style = 'maxstore_theme_stylesheets'; // This is 'twentyfifteen-style' for the Twenty Fifteen theme.
wp_enqueue_style( $parent_style, get_template_directory_uri() . '/style.css' );
wp_enqueue_style( $parent_style, get_template_directory_uri() . '/css/bootstrap.css' );
wp_enqueue_style( 'child-style', get_stylesheet_directory_uri() . '/style.css', array( $parent_style ), wp_get_theme()->get('Version'));
wp_enqueue_style( 'child-style', get_stylesheet_directory_uri() . '/css/bootstrap.css', array( $parent_style ), wp_get_theme()->get('Version'));
}
add_action( 'wp_enqueue_scripts', 'my_theme_enqueue_styles' );
?>
```
**EDIT 2:**
My bootstrap stylesheet is getting loaded, but for some reason my website is still using another version of it. As you can see it uses 3 times the same styles and the one that is really used is version 3.3.4. and I want to use the one with the blue color which is version 1.0.2
[](https://i.stack.imgur.com/SkvA9.png)
Version 3.3.4 in the picture and I want to use the bootstrap version 1.0.2.
[](https://i.stack.imgur.com/9ygYt.png)
**EDIT 3:**
Code from functions.php that I am using at the moment
```
<?php
function my_theme_enqueue_styles() {
$parent_styles = array('maxstore_theme_style', 'maxstore_theme_bootstrap');
// This is 'twentyfifteen-style' for the Twenty Fifteen theme.
wp_enqueue_style( $parent_styles[0], get_template_directory_uri() .
'/style.css' );
wp_enqueue_style( $parent_styles[1], get_template_directory_uri() .
'/css/bootstrap.css' );
wp_enqueue_style( 'child-style', get_stylesheet_directory_uri() .
'/style.css', $parent_styles, wp_get_theme()->get('Version'));
wp_enqueue_style( 'child-bootstrap', get_stylesheet_directory_uri() .
'/css/bootstrap.css', $parent_styles, wp_get_theme()->get('Version'));
}
add_action( 'wp_enqueue_scripts', 'my_theme_enqueue_styles' );
?>
``` | Parent vs Child Themes
----------------------
`get_template_directory_uri` always refers to the parent theme you can verify this as you always should when things don't load as expected by looking in the console in the browsers dev tools. These would show 404 errors for the CSS files, in the wrong folder.
Instead, use `get_stylesheet_directory_uri`, the `stylesheet` family of functions always refer to the current active theme
Duplicated Names
----------------
```
wp_enqueue_style( 'child-style', get_stylesheet_directory_uri() . '/style.css', array( $parent_style ), wp_get_theme()->get('Version'));
wp_enqueue_style( 'child-style', get_stylesheet_directory_uri() . '/css/bootstrap.css', array( $parent_style ), wp_get_theme()->get('Version'));
```
You can't call 2 stylesheets the same thing and expect it to work, which is what you've done with all 4 of your stylesheets
Also notice that you've loaded `bootstrap.css` from both themes |
289,342 | <p>Where in the database can I find that a product is marked "featured"?
I have marked 4 products as featured but I have yet to find out how to retrieve this information from any the database tables.</p>
<p>Thank you.</p>
| [
{
"answer_id": 289322,
"author": "Tom J Nowell",
"author_id": 736,
"author_profile": "https://wordpress.stackexchange.com/users/736",
"pm_score": 3,
"selected": true,
"text": "<h2>Parent vs Child Themes</h2>\n\n<p><code>get_template_directory_uri</code> always refers to the parent theme you can verify this as you always should when things don't load as expected by looking in the console in the browsers dev tools. These would show 404 errors for the CSS files, in the wrong folder.</p>\n\n<p>Instead, use <code>get_stylesheet_directory_uri</code>, the <code>stylesheet</code> family of functions always refer to the current active theme</p>\n\n<h2>Duplicated Names</h2>\n\n<pre><code>wp_enqueue_style( 'child-style', get_stylesheet_directory_uri() . '/style.css', array( $parent_style ), wp_get_theme()->get('Version'));\nwp_enqueue_style( 'child-style', get_stylesheet_directory_uri() . '/css/bootstrap.css', array( $parent_style ), wp_get_theme()->get('Version'));\n</code></pre>\n\n<p>You can't call 2 stylesheets the same thing and expect it to work, which is what you've done with all 4 of your stylesheets</p>\n\n<p>Also notice that you've loaded <code>bootstrap.css</code> from both themes</p>\n"
},
{
"answer_id": 289368,
"author": "Landing on Jupiter",
"author_id": 74534,
"author_profile": "https://wordpress.stackexchange.com/users/74534",
"pm_score": 2,
"selected": false,
"text": "<p>Each enqueue request needs a unique handle (or name), which is the first argument in the <a href=\"https://developer.wordpress.org/reference/functions/wp_enqueue_style/\" rel=\"nofollow noreferrer\">wp_enqueue_style hook</a>. Since your first two and last two commands are given the same handle, it's probably only loading two of the four. </p>\n\n<p>Try this. I followed your model of declaring a variable for the Parent Style handle. I've replaced $parent_style with an array containing two unique handles. Note that this means the dependency statement no longer needs an array, since the variable we're using is already one, as reflected in my code.</p>\n\n<pre><code><?php\nfunction my_theme_enqueue_styles() {\n $parent_styles = array( 'maxstore_theme_style', 'maxstore_theme_bootstrap' );\n wp_enqueue_style( $parent_styles[0], get_template_directory_uri() . '/style.css' );\n wp_enqueue_style( $parent_styles[1], get_template_directory_uri() . '/css/bootstrap.css' );\n wp_enqueue_style( 'child-style', get_stylesheet_directory_uri() . '/style.css', $parent_styles, wp_get_theme()->get('Version'));\n wp_enqueue_style( 'child-bootstrap', get_stylesheet_directory_uri() . '/css/bootstrap.css', $parent_styles, wp_get_theme()->get('Version'));\n}\nadd_action( 'wp_enqueue_scripts', 'my_theme_enqueue_styles' );\n?>\n</code></pre>\n"
}
]
| 2017/12/23 | [
"https://wordpress.stackexchange.com/questions/289342",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/131388/"
]
| Where in the database can I find that a product is marked "featured"?
I have marked 4 products as featured but I have yet to find out how to retrieve this information from any the database tables.
Thank you. | Parent vs Child Themes
----------------------
`get_template_directory_uri` always refers to the parent theme you can verify this as you always should when things don't load as expected by looking in the console in the browsers dev tools. These would show 404 errors for the CSS files, in the wrong folder.
Instead, use `get_stylesheet_directory_uri`, the `stylesheet` family of functions always refer to the current active theme
Duplicated Names
----------------
```
wp_enqueue_style( 'child-style', get_stylesheet_directory_uri() . '/style.css', array( $parent_style ), wp_get_theme()->get('Version'));
wp_enqueue_style( 'child-style', get_stylesheet_directory_uri() . '/css/bootstrap.css', array( $parent_style ), wp_get_theme()->get('Version'));
```
You can't call 2 stylesheets the same thing and expect it to work, which is what you've done with all 4 of your stylesheets
Also notice that you've loaded `bootstrap.css` from both themes |
289,349 | <p>Is there a way to globally change the font size for Heading 1, Heading 2, Heading 3, etc.
So, for example, if I want to change the font size for everything tagged with H2, every H2 text size on every page in the site changes.</p>
<p>Thank you.</p>
| [
{
"answer_id": 289356,
"author": "Arsalan Mithani",
"author_id": 111402,
"author_profile": "https://wordpress.stackexchange.com/users/111402",
"pm_score": 1,
"selected": false,
"text": "<p>Depends on the theme you are using, some themes have general settings panel labelled as <strong>Theme Options</strong> where you can change general & global settings like skins, typography etc. If you don't have any theme option panel do it with css: <code>h1{ font-size: 24px;}</code>, if css doesn't work apply <code>!important</code> tag to change it forcefully <code>h1{ font-size: 24px !important;}, h2{ font-size: 20px !important;}</code> etc...</p>\n"
},
{
"answer_id": 290097,
"author": "Jonathan Guerin",
"author_id": 133461,
"author_profile": "https://wordpress.stackexchange.com/users/133461",
"pm_score": 1,
"selected": false,
"text": "<p>Of course.</p>\n\n<p>Within your styles.css file, simply change the tag that you require as follows:</p>\n\n<pre><code>h1 {\n font-size: X px;\n}\n</code></pre>\n\n<p>Now, if only it was that easy, right?</p>\n\n<p>Here are a few things you need to <strong>take care of</strong>:</p>\n\n<p>1) Plugins</p>\n\n<p>The way plugins work is that they sometimes play with these settings too and based on which property loaded the last, that'll be your setting!</p>\n\n<p>Check this out:</p>\n\n<p>If <code>styles.css</code> had the declaration of</p>\n\n<p><code>h1 { font-size: 12px; }</code> but along comes a plugin that loads some other CSS and says <code>h1 { font-size: 14px }</code> guess what happens?</p>\n\n<p>The <code>h1</code> now has a font size of 14px.</p>\n\n<p>The only real way to ensure your styles will always over-write anything else is to either declare them via JS, which has a <code>post-css</code> execution script, meaning it executes after CSS, but this will be over-kill in terms of performance or simply make sure you manage your rules correctly.</p>\n\n<p>Additionally, you can use the <code>!important</code> declaration in your styles.css file, but I find this hacky, due to:</p>\n\n<p>2) User Changes</p>\n\n<p>If you plan on having a dynamic theme and you allow users to change your ,<code><h1></code> size with <code>set_option</code>, you'll have issues unless you also declare that with <code>!important</code>.</p>\n\n<p>Hope this helps.</p>\n"
},
{
"answer_id": 290167,
"author": "andrewsandlin",
"author_id": 131642,
"author_profile": "https://wordpress.stackexchange.com/users/131642",
"pm_score": 2,
"selected": false,
"text": "<p>Sure, locate the style.css file within your theme and paste the code below. I suggest using percentages in your declarations so as to keep the base size styling hopefully already in your theme.</p>\n\n<pre><code>h1 { font-size: 150%; }\nh2 { font-size: 140%; }\nh3 { font-size: 130%; }\nh4 { font-size: 120%; }\nh5 { font-size: 110%; }\n</code></pre>\n"
},
{
"answer_id": 290169,
"author": "Cedon",
"author_id": 80069,
"author_profile": "https://wordpress.stackexchange.com/users/80069",
"pm_score": 1,
"selected": false,
"text": "<p>It may not be the best solution to change these elements directly. For example, some themes like Automattic's own <code>_s</code> use a conditional to display the post/page title or site title.</p>\n\n<p>For example, if you're on the site's index page, then the site title may be <code><h1 class=\"site-title\">Site Title</h1></code> where as on a single post it might be <code><p class=\"site-title\">Site Title</p></code> because on that particular page, the post title is more important.</p>\n"
}
]
| 2017/12/23 | [
"https://wordpress.stackexchange.com/questions/289349",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/132968/"
]
| Is there a way to globally change the font size for Heading 1, Heading 2, Heading 3, etc.
So, for example, if I want to change the font size for everything tagged with H2, every H2 text size on every page in the site changes.
Thank you. | Sure, locate the style.css file within your theme and paste the code below. I suggest using percentages in your declarations so as to keep the base size styling hopefully already in your theme.
```
h1 { font-size: 150%; }
h2 { font-size: 140%; }
h3 { font-size: 130%; }
h4 { font-size: 120%; }
h5 { font-size: 110%; }
``` |
289,387 | <p>how can I remove default pagination on woocommerce shop page ?
and then use my custom pagination (or use pagination plugin) on woocommerce shop page</p>
<p>thank you</p>
| [
{
"answer_id": 289565,
"author": "D. Dan",
"author_id": 133528,
"author_profile": "https://wordpress.stackexchange.com/users/133528",
"pm_score": 2,
"selected": false,
"text": "<p>You need to locate the right file in the plugins/woocommerce/templates directory and make a woocommerce directory in your theme or child theme and copy it there, and edit it to your liking.</p>\n\n<p>Or you could find the action that puts it there in the first place and remove it with remove_action in your theme-s functions.php.</p>\n"
},
{
"answer_id": 304604,
"author": "Mostafa Norzade",
"author_id": 131388,
"author_profile": "https://wordpress.stackexchange.com/users/131388",
"pm_score": 3,
"selected": true,
"text": "<p>I found the answer :</p>\n\n<p>1) remove woocommerce pagination in theme functions.php :</p>\n\n<pre><code>remove_action( 'woocommerce_before_shop_loop', 'storefront_woocommerce_pagination', 30 );\n</code></pre>\n\n<p><a href=\"https://github.com/woocommerce/storefront/blob/8c510114a14f622e2219178a47c7da6d11556cb7/inc/woocommerce/storefront-woocommerce-template-hooks.php\" rel=\"nofollow noreferrer\">storefront woocommerce template hooks</a></p>\n\n<p>2) use the below code for customize your pagination in functions.php :</p>\n\n<pre><code> function bittersweet_pagination() {\n\nglobal $wp_query;\n\n$big = 999999999; // need an unlikely integer\n\n$pages = paginate_links( array(\n 'base' => str_replace( $big, '%#%', esc_url( get_pagenum_link( $big ) ) ),\n 'format' => '?paged=%#%',\n 'current' => max( 1, get_query_var('paged') ),\n 'total' => $wp_query->max_num_pages,\n 'type' => 'array',\n ) );\n if( is_array( $pages ) ) {\n $paged = ( get_query_var('paged') == 0 ) ? 1 : get_query_var('paged');\n echo '<div class=\"pagination-wrap\"><ul class=\"pagination\">';\n foreach ( $pages as $page ) {\n echo \"<li>$page</li>\";\n }\n echo '</ul></div>';\n }\n}\n</code></pre>\n"
},
{
"answer_id": 328436,
"author": "ttn_",
"author_id": 91856,
"author_profile": "https://wordpress.stackexchange.com/users/91856",
"pm_score": 2,
"selected": false,
"text": "<p>Add below code in file <code>functions.php</code>:</p>\n\n<pre>remove_action( 'woocommerce_after_shop_loop', 'woocommerce_pagination', 10 );</pre>\n"
},
{
"answer_id": 409609,
"author": "Jayden Lawson",
"author_id": 58378,
"author_profile": "https://wordpress.stackexchange.com/users/58378",
"pm_score": 0,
"selected": false,
"text": "<p>This page on the WooCommerce website gave a better answer for me than anything answers on this page: <a href=\"https://woocommerce.com/document/change-number-of-products-displayed-per-page/\" rel=\"nofollow noreferrer\">https://woocommerce.com/document/change-number-of-products-displayed-per-page/</a></p>\n"
}
]
| 2017/12/24 | [
"https://wordpress.stackexchange.com/questions/289387",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/131388/"
]
| how can I remove default pagination on woocommerce shop page ?
and then use my custom pagination (or use pagination plugin) on woocommerce shop page
thank you | I found the answer :
1) remove woocommerce pagination in theme functions.php :
```
remove_action( 'woocommerce_before_shop_loop', 'storefront_woocommerce_pagination', 30 );
```
[storefront woocommerce template hooks](https://github.com/woocommerce/storefront/blob/8c510114a14f622e2219178a47c7da6d11556cb7/inc/woocommerce/storefront-woocommerce-template-hooks.php)
2) use the below code for customize your pagination in functions.php :
```
function bittersweet_pagination() {
global $wp_query;
$big = 999999999; // need an unlikely integer
$pages = paginate_links( array(
'base' => str_replace( $big, '%#%', esc_url( get_pagenum_link( $big ) ) ),
'format' => '?paged=%#%',
'current' => max( 1, get_query_var('paged') ),
'total' => $wp_query->max_num_pages,
'type' => 'array',
) );
if( is_array( $pages ) ) {
$paged = ( get_query_var('paged') == 0 ) ? 1 : get_query_var('paged');
echo '<div class="pagination-wrap"><ul class="pagination">';
foreach ( $pages as $page ) {
echo "<li>$page</li>";
}
echo '</ul></div>';
}
}
``` |
289,399 | <p>hi i need your help regarding for woo-commerce product title based search
we have list of product my searching keyword available in product title need to show list product. if product title don't have my search keyword but available in product description section this don't need to display this product. </p>
| [
{
"answer_id": 289565,
"author": "D. Dan",
"author_id": 133528,
"author_profile": "https://wordpress.stackexchange.com/users/133528",
"pm_score": 2,
"selected": false,
"text": "<p>You need to locate the right file in the plugins/woocommerce/templates directory and make a woocommerce directory in your theme or child theme and copy it there, and edit it to your liking.</p>\n\n<p>Or you could find the action that puts it there in the first place and remove it with remove_action in your theme-s functions.php.</p>\n"
},
{
"answer_id": 304604,
"author": "Mostafa Norzade",
"author_id": 131388,
"author_profile": "https://wordpress.stackexchange.com/users/131388",
"pm_score": 3,
"selected": true,
"text": "<p>I found the answer :</p>\n\n<p>1) remove woocommerce pagination in theme functions.php :</p>\n\n<pre><code>remove_action( 'woocommerce_before_shop_loop', 'storefront_woocommerce_pagination', 30 );\n</code></pre>\n\n<p><a href=\"https://github.com/woocommerce/storefront/blob/8c510114a14f622e2219178a47c7da6d11556cb7/inc/woocommerce/storefront-woocommerce-template-hooks.php\" rel=\"nofollow noreferrer\">storefront woocommerce template hooks</a></p>\n\n<p>2) use the below code for customize your pagination in functions.php :</p>\n\n<pre><code> function bittersweet_pagination() {\n\nglobal $wp_query;\n\n$big = 999999999; // need an unlikely integer\n\n$pages = paginate_links( array(\n 'base' => str_replace( $big, '%#%', esc_url( get_pagenum_link( $big ) ) ),\n 'format' => '?paged=%#%',\n 'current' => max( 1, get_query_var('paged') ),\n 'total' => $wp_query->max_num_pages,\n 'type' => 'array',\n ) );\n if( is_array( $pages ) ) {\n $paged = ( get_query_var('paged') == 0 ) ? 1 : get_query_var('paged');\n echo '<div class=\"pagination-wrap\"><ul class=\"pagination\">';\n foreach ( $pages as $page ) {\n echo \"<li>$page</li>\";\n }\n echo '</ul></div>';\n }\n}\n</code></pre>\n"
},
{
"answer_id": 328436,
"author": "ttn_",
"author_id": 91856,
"author_profile": "https://wordpress.stackexchange.com/users/91856",
"pm_score": 2,
"selected": false,
"text": "<p>Add below code in file <code>functions.php</code>:</p>\n\n<pre>remove_action( 'woocommerce_after_shop_loop', 'woocommerce_pagination', 10 );</pre>\n"
},
{
"answer_id": 409609,
"author": "Jayden Lawson",
"author_id": 58378,
"author_profile": "https://wordpress.stackexchange.com/users/58378",
"pm_score": 0,
"selected": false,
"text": "<p>This page on the WooCommerce website gave a better answer for me than anything answers on this page: <a href=\"https://woocommerce.com/document/change-number-of-products-displayed-per-page/\" rel=\"nofollow noreferrer\">https://woocommerce.com/document/change-number-of-products-displayed-per-page/</a></p>\n"
}
]
| 2017/12/24 | [
"https://wordpress.stackexchange.com/questions/289399",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/114102/"
]
| hi i need your help regarding for woo-commerce product title based search
we have list of product my searching keyword available in product title need to show list product. if product title don't have my search keyword but available in product description section this don't need to display this product. | I found the answer :
1) remove woocommerce pagination in theme functions.php :
```
remove_action( 'woocommerce_before_shop_loop', 'storefront_woocommerce_pagination', 30 );
```
[storefront woocommerce template hooks](https://github.com/woocommerce/storefront/blob/8c510114a14f622e2219178a47c7da6d11556cb7/inc/woocommerce/storefront-woocommerce-template-hooks.php)
2) use the below code for customize your pagination in functions.php :
```
function bittersweet_pagination() {
global $wp_query;
$big = 999999999; // need an unlikely integer
$pages = paginate_links( array(
'base' => str_replace( $big, '%#%', esc_url( get_pagenum_link( $big ) ) ),
'format' => '?paged=%#%',
'current' => max( 1, get_query_var('paged') ),
'total' => $wp_query->max_num_pages,
'type' => 'array',
) );
if( is_array( $pages ) ) {
$paged = ( get_query_var('paged') == 0 ) ? 1 : get_query_var('paged');
echo '<div class="pagination-wrap"><ul class="pagination">';
foreach ( $pages as $page ) {
echo "<li>$page</li>";
}
echo '</ul></div>';
}
}
``` |
289,421 | <p>While writing a custom element for WC Bakery (formerly Visual Composer) I've discovered that the HTML tags are being stripped from the <code>textfield</code> parameter type. It's sanitizing the <code>textfield</code> value by default. </p>
<p>I could not find a way to disable the <code>textfield</code> sanitization. </p>
<p>How can I allow HTML tags to be entered into this field?</p>
| [
{
"answer_id": 315493,
"author": "rtpHarry",
"author_id": 60500,
"author_profile": "https://wordpress.stackexchange.com/users/60500",
"pm_score": 2,
"selected": false,
"text": "<p>You need to change the type from <code>textarea</code> to <code>textarea_raw_html</code>:</p>\n\n<ul>\n<li><a href=\"https://kb.wpbakery.com/docs/inner-api/vc_map/\" rel=\"nofollow noreferrer\">https://kb.wpbakery.com/docs/inner-api/vc_map/</a> </li>\n</ul>\n\n<p>Under the section \"Available type values\" it says:</p>\n\n<blockquote>\n <p>textarea_raw_html: Text area, its content will be coded into base64 (this allows you to store raw js or raw html code)</p>\n</blockquote>\n\n<p>Although I'm not sure why they can base64 encode the output from this but not the <code>textarea_html</code> box with its nice formatting - an annoying limitation.</p>\n\n<p><strong>UPDATE</strong> It looks like you have to jump through some hoops when you switch to the <code>textarea_raw_html</code> param type. </p>\n\n<p>To use the value you need to manually decode it with:</p>\n\n<pre><code>$atts['some_param'] = rawurldecode( base64_decode( $atts['some_param'] ) );\n</code></pre>\n"
},
{
"answer_id": 359134,
"author": "Javier Angelelli",
"author_id": 183076,
"author_profile": "https://wordpress.stackexchange.com/users/183076",
"pm_score": 0,
"selected": false,
"text": "<p>If you pass the vc_map param as param_name = 'content' the html wont get stripped off. The problem is you can only put one content.</p>\n\n<pre><code>array(\n 'type' => 'textarea',\n 'heading' => esc_html__( 'Texto', 'bauhaus' ),\n 'param_name' => 'content',\n 'holder' => 'div'\n ),\n</code></pre>\n\n<pre><code>add_shortcode( 'custom_bloque_informativo', 'custom_bloque_informativo_func' );\nfunction custom_bloque_informativo_func( $atts, $content ) {\n ob_start();\n}\n</code></pre>\n"
}
]
| 2017/12/25 | [
"https://wordpress.stackexchange.com/questions/289421",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/75264/"
]
| While writing a custom element for WC Bakery (formerly Visual Composer) I've discovered that the HTML tags are being stripped from the `textfield` parameter type. It's sanitizing the `textfield` value by default.
I could not find a way to disable the `textfield` sanitization.
How can I allow HTML tags to be entered into this field? | You need to change the type from `textarea` to `textarea_raw_html`:
* <https://kb.wpbakery.com/docs/inner-api/vc_map/>
Under the section "Available type values" it says:
>
> textarea\_raw\_html: Text area, its content will be coded into base64 (this allows you to store raw js or raw html code)
>
>
>
Although I'm not sure why they can base64 encode the output from this but not the `textarea_html` box with its nice formatting - an annoying limitation.
**UPDATE** It looks like you have to jump through some hoops when you switch to the `textarea_raw_html` param type.
To use the value you need to manually decode it with:
```
$atts['some_param'] = rawurldecode( base64_decode( $atts['some_param'] ) );
``` |
289,435 | <p>I'd like to move all my assets (CSS, JS, Images, Fonts) in an asset folder in my theme.</p>
<p>I did it very well for the fonts and images. For the CSS, I just kept the style.css with the style meta information in it (as advised <a href="https://wordpress.stackexchange.com/a/111505/133812">here</a>).</p>
<p>But I'm using the great underscores.me starter theme for Wordpress and I have in my theme a JS folder containing customizer, navigation.js and skip-link-focus-fix.js</p>
<p>All these scripts are included in my footer via the wp_footer() function. So, if I move these scripts to my /assets/js/ folder, I have three missing files called in the footer.</p>
<p>Is there a way to (1) not load these scripts or (2) change the directory and tell the wp_footer to call /assets/js and not /js/ ?</p>
<p>Thank you for your help.</p>
| [
{
"answer_id": 289441,
"author": "Serkan Algur",
"author_id": 23042,
"author_profile": "https://wordpress.stackexchange.com/users/23042",
"pm_score": 2,
"selected": true,
"text": "<p>go to your themes <code>functions.php</code> and find line 122. You will find navigation.js function.</p>\n\n<pre><code>get_template_directory_uri() . '/js/navigation.js\n</code></pre>\n\n<p>and change it to</p>\n\n<pre><code>get_template_directory_uri() . 'assets/js/navigation.js\n</code></pre>\n\n<p>do it again for <code>skip-link-focus-fix.js</code> code located on line 124.</p>\n\n<p>For customizer go and find <code>customizer.php</code> in 'inc' folder. Go line 53 and change <code>js/customizer.js</code> code to <code>assets/js/customizer.js</code></p>\n\n<p>Don't forget to move your files :)</p>\n"
},
{
"answer_id": 289442,
"author": "Badr",
"author_id": 121783,
"author_profile": "https://wordpress.stackexchange.com/users/121783",
"pm_score": 0,
"selected": false,
"text": "<p>These scripts are enqueued in functions.php using function wp_enqueue_script(). So open your functions.php file, search for these scripts then remove the call so as not to load them, or change the path to your new directory.</p>\n"
}
]
| 2017/12/25 | [
"https://wordpress.stackexchange.com/questions/289435",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/133812/"
]
| I'd like to move all my assets (CSS, JS, Images, Fonts) in an asset folder in my theme.
I did it very well for the fonts and images. For the CSS, I just kept the style.css with the style meta information in it (as advised [here](https://wordpress.stackexchange.com/a/111505/133812)).
But I'm using the great underscores.me starter theme for Wordpress and I have in my theme a JS folder containing customizer, navigation.js and skip-link-focus-fix.js
All these scripts are included in my footer via the wp\_footer() function. So, if I move these scripts to my /assets/js/ folder, I have three missing files called in the footer.
Is there a way to (1) not load these scripts or (2) change the directory and tell the wp\_footer to call /assets/js and not /js/ ?
Thank you for your help. | go to your themes `functions.php` and find line 122. You will find navigation.js function.
```
get_template_directory_uri() . '/js/navigation.js
```
and change it to
```
get_template_directory_uri() . 'assets/js/navigation.js
```
do it again for `skip-link-focus-fix.js` code located on line 124.
For customizer go and find `customizer.php` in 'inc' folder. Go line 53 and change `js/customizer.js` code to `assets/js/customizer.js`
Don't forget to move your files :) |
289,462 | <p>So i came to three posible solutions to this question and can't decide which is better. What is your opinion?</p>
<p>First solution:</p>
<pre><code>if ( ( in_array('administrator', userdata('role')) || in_array('editor',
userdata('role')) ) == false)
{
add_filter('show_admin_bar', '__return_false');
}
</code></pre>
<p>Second one:</p>
<pre><code>if( ( current_user_can('editor') || current_user_can('administrator') ) == false )
{
add_filter('show_admin_bar', '__return_false');
}
</code></pre>
<p>Third one:</p>
<pre><code>$allowed_roles = array('editor', 'administrator');
if( array_intersect($allowed_roles, userdata('role') ) == false ) {
add_filter('show_admin_bar', '__return_false');
}
</code></pre>
<p>User data function:</p>
<pre><code>function userdata($userdata){
$userinfo = wp_get_current_user();
if ($userdata == 'nick')
return $userinfo ->user_login;
if ($userdata == 'mail')
return $userinfo ->user_email;
if ($userdata == 'id')
return $userinfo ->ID;
if ($userdata == 'role')
return $userinfo ->roles;
else
return 'Eror';
}
</code></pre>
<p>I am voting for the third solution.</p>
| [
{
"answer_id": 289441,
"author": "Serkan Algur",
"author_id": 23042,
"author_profile": "https://wordpress.stackexchange.com/users/23042",
"pm_score": 2,
"selected": true,
"text": "<p>go to your themes <code>functions.php</code> and find line 122. You will find navigation.js function.</p>\n\n<pre><code>get_template_directory_uri() . '/js/navigation.js\n</code></pre>\n\n<p>and change it to</p>\n\n<pre><code>get_template_directory_uri() . 'assets/js/navigation.js\n</code></pre>\n\n<p>do it again for <code>skip-link-focus-fix.js</code> code located on line 124.</p>\n\n<p>For customizer go and find <code>customizer.php</code> in 'inc' folder. Go line 53 and change <code>js/customizer.js</code> code to <code>assets/js/customizer.js</code></p>\n\n<p>Don't forget to move your files :)</p>\n"
},
{
"answer_id": 289442,
"author": "Badr",
"author_id": 121783,
"author_profile": "https://wordpress.stackexchange.com/users/121783",
"pm_score": 0,
"selected": false,
"text": "<p>These scripts are enqueued in functions.php using function wp_enqueue_script(). So open your functions.php file, search for these scripts then remove the call so as not to load them, or change the path to your new directory.</p>\n"
}
]
| 2017/12/25 | [
"https://wordpress.stackexchange.com/questions/289462",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/133829/"
]
| So i came to three posible solutions to this question and can't decide which is better. What is your opinion?
First solution:
```
if ( ( in_array('administrator', userdata('role')) || in_array('editor',
userdata('role')) ) == false)
{
add_filter('show_admin_bar', '__return_false');
}
```
Second one:
```
if( ( current_user_can('editor') || current_user_can('administrator') ) == false )
{
add_filter('show_admin_bar', '__return_false');
}
```
Third one:
```
$allowed_roles = array('editor', 'administrator');
if( array_intersect($allowed_roles, userdata('role') ) == false ) {
add_filter('show_admin_bar', '__return_false');
}
```
User data function:
```
function userdata($userdata){
$userinfo = wp_get_current_user();
if ($userdata == 'nick')
return $userinfo ->user_login;
if ($userdata == 'mail')
return $userinfo ->user_email;
if ($userdata == 'id')
return $userinfo ->ID;
if ($userdata == 'role')
return $userinfo ->roles;
else
return 'Eror';
}
```
I am voting for the third solution. | go to your themes `functions.php` and find line 122. You will find navigation.js function.
```
get_template_directory_uri() . '/js/navigation.js
```
and change it to
```
get_template_directory_uri() . 'assets/js/navigation.js
```
do it again for `skip-link-focus-fix.js` code located on line 124.
For customizer go and find `customizer.php` in 'inc' folder. Go line 53 and change `js/customizer.js` code to `assets/js/customizer.js`
Don't forget to move your files :) |
289,474 | <p>Whenever I post a new post or page, the website serves a 301 redirect to the homepage. All existing posts are working correctly (not redirecting). </p>
<p>What I've tried:<br>
- Checked console and confirm APACHE is serving 301<br>
- Tried to re-save permalinks from Wordpress<br>
- Checked .htaccess for anything out of the ordinary </p>
<p>The problem was cause by previous developers and I'm unable to trace their work. </p>
<p>Any help is appreciated, thanks.</p>
| [
{
"answer_id": 289441,
"author": "Serkan Algur",
"author_id": 23042,
"author_profile": "https://wordpress.stackexchange.com/users/23042",
"pm_score": 2,
"selected": true,
"text": "<p>go to your themes <code>functions.php</code> and find line 122. You will find navigation.js function.</p>\n\n<pre><code>get_template_directory_uri() . '/js/navigation.js\n</code></pre>\n\n<p>and change it to</p>\n\n<pre><code>get_template_directory_uri() . 'assets/js/navigation.js\n</code></pre>\n\n<p>do it again for <code>skip-link-focus-fix.js</code> code located on line 124.</p>\n\n<p>For customizer go and find <code>customizer.php</code> in 'inc' folder. Go line 53 and change <code>js/customizer.js</code> code to <code>assets/js/customizer.js</code></p>\n\n<p>Don't forget to move your files :)</p>\n"
},
{
"answer_id": 289442,
"author": "Badr",
"author_id": 121783,
"author_profile": "https://wordpress.stackexchange.com/users/121783",
"pm_score": 0,
"selected": false,
"text": "<p>These scripts are enqueued in functions.php using function wp_enqueue_script(). So open your functions.php file, search for these scripts then remove the call so as not to load them, or change the path to your new directory.</p>\n"
}
]
| 2017/12/26 | [
"https://wordpress.stackexchange.com/questions/289474",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/133834/"
]
| Whenever I post a new post or page, the website serves a 301 redirect to the homepage. All existing posts are working correctly (not redirecting).
What I've tried:
- Checked console and confirm APACHE is serving 301
- Tried to re-save permalinks from Wordpress
- Checked .htaccess for anything out of the ordinary
The problem was cause by previous developers and I'm unable to trace their work.
Any help is appreciated, thanks. | go to your themes `functions.php` and find line 122. You will find navigation.js function.
```
get_template_directory_uri() . '/js/navigation.js
```
and change it to
```
get_template_directory_uri() . 'assets/js/navigation.js
```
do it again for `skip-link-focus-fix.js` code located on line 124.
For customizer go and find `customizer.php` in 'inc' folder. Go line 53 and change `js/customizer.js` code to `assets/js/customizer.js`
Don't forget to move your files :) |
289,516 | <p>I need to add a bus timings category for a client.</p>
<p>I need to have </p>
<p>FROM STOP (selectable field)
TO STOP (selectable field)
START HOUR (selectable field but optional)
END HOUR (selectable field but optional)</p>
<p>take these inputs and show results with running buses in table within those times.</p>
<p>similar to this one </p>
<p>stackoverflow.com/questions/40524279/need-mysql-query-for-search-bus-from-stop-and-to-stop</p>
<p>Which do i use CPT or meta fields ?</p>
<p>Kindly help me get started.</p>
| [
{
"answer_id": 289441,
"author": "Serkan Algur",
"author_id": 23042,
"author_profile": "https://wordpress.stackexchange.com/users/23042",
"pm_score": 2,
"selected": true,
"text": "<p>go to your themes <code>functions.php</code> and find line 122. You will find navigation.js function.</p>\n\n<pre><code>get_template_directory_uri() . '/js/navigation.js\n</code></pre>\n\n<p>and change it to</p>\n\n<pre><code>get_template_directory_uri() . 'assets/js/navigation.js\n</code></pre>\n\n<p>do it again for <code>skip-link-focus-fix.js</code> code located on line 124.</p>\n\n<p>For customizer go and find <code>customizer.php</code> in 'inc' folder. Go line 53 and change <code>js/customizer.js</code> code to <code>assets/js/customizer.js</code></p>\n\n<p>Don't forget to move your files :)</p>\n"
},
{
"answer_id": 289442,
"author": "Badr",
"author_id": 121783,
"author_profile": "https://wordpress.stackexchange.com/users/121783",
"pm_score": 0,
"selected": false,
"text": "<p>These scripts are enqueued in functions.php using function wp_enqueue_script(). So open your functions.php file, search for these scripts then remove the call so as not to load them, or change the path to your new directory.</p>\n"
}
]
| 2017/12/26 | [
"https://wordpress.stackexchange.com/questions/289516",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/133860/"
]
| I need to add a bus timings category for a client.
I need to have
FROM STOP (selectable field)
TO STOP (selectable field)
START HOUR (selectable field but optional)
END HOUR (selectable field but optional)
take these inputs and show results with running buses in table within those times.
similar to this one
stackoverflow.com/questions/40524279/need-mysql-query-for-search-bus-from-stop-and-to-stop
Which do i use CPT or meta fields ?
Kindly help me get started. | go to your themes `functions.php` and find line 122. You will find navigation.js function.
```
get_template_directory_uri() . '/js/navigation.js
```
and change it to
```
get_template_directory_uri() . 'assets/js/navigation.js
```
do it again for `skip-link-focus-fix.js` code located on line 124.
For customizer go and find `customizer.php` in 'inc' folder. Go line 53 and change `js/customizer.js` code to `assets/js/customizer.js`
Don't forget to move your files :) |
289,520 | <p>I am tasked with updating plugins and core on a number of blogs that I am completely unfamiliar with (nothing weird about them, but I haven't worked with them before today). </p>
<p>What I need to do is update all the plugins and the core, and after it's done fix or rollback any introduced bugs. Thing is, I don't have shell access and I don't have access to a home directory on the server, so I can't automate a lot, or I don't know how to automate anything that will run tests or the like after every update to make sure that nothing is broken.</p>
<p>These are fairly large sites, so there are a lot of places bugs can hide. Is there a recommended procedure for this? Or is there a way that I can pretty well reliably catch any new bugs introduced? </p>
<p>I'm not worried about temporary errors, because this is a staging environment, but I do want comprehensive knowledge that nothing is busted. I should have access to error_log files, but I'm not 100% sure I do yet, and I haven't seen any.</p>
<p>Any help?</p>
| [
{
"answer_id": 289441,
"author": "Serkan Algur",
"author_id": 23042,
"author_profile": "https://wordpress.stackexchange.com/users/23042",
"pm_score": 2,
"selected": true,
"text": "<p>go to your themes <code>functions.php</code> and find line 122. You will find navigation.js function.</p>\n\n<pre><code>get_template_directory_uri() . '/js/navigation.js\n</code></pre>\n\n<p>and change it to</p>\n\n<pre><code>get_template_directory_uri() . 'assets/js/navigation.js\n</code></pre>\n\n<p>do it again for <code>skip-link-focus-fix.js</code> code located on line 124.</p>\n\n<p>For customizer go and find <code>customizer.php</code> in 'inc' folder. Go line 53 and change <code>js/customizer.js</code> code to <code>assets/js/customizer.js</code></p>\n\n<p>Don't forget to move your files :)</p>\n"
},
{
"answer_id": 289442,
"author": "Badr",
"author_id": 121783,
"author_profile": "https://wordpress.stackexchange.com/users/121783",
"pm_score": 0,
"selected": false,
"text": "<p>These scripts are enqueued in functions.php using function wp_enqueue_script(). So open your functions.php file, search for these scripts then remove the call so as not to load them, or change the path to your new directory.</p>\n"
}
]
| 2017/12/26 | [
"https://wordpress.stackexchange.com/questions/289520",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/65569/"
]
| I am tasked with updating plugins and core on a number of blogs that I am completely unfamiliar with (nothing weird about them, but I haven't worked with them before today).
What I need to do is update all the plugins and the core, and after it's done fix or rollback any introduced bugs. Thing is, I don't have shell access and I don't have access to a home directory on the server, so I can't automate a lot, or I don't know how to automate anything that will run tests or the like after every update to make sure that nothing is broken.
These are fairly large sites, so there are a lot of places bugs can hide. Is there a recommended procedure for this? Or is there a way that I can pretty well reliably catch any new bugs introduced?
I'm not worried about temporary errors, because this is a staging environment, but I do want comprehensive knowledge that nothing is busted. I should have access to error\_log files, but I'm not 100% sure I do yet, and I haven't seen any.
Any help? | go to your themes `functions.php` and find line 122. You will find navigation.js function.
```
get_template_directory_uri() . '/js/navigation.js
```
and change it to
```
get_template_directory_uri() . 'assets/js/navigation.js
```
do it again for `skip-link-focus-fix.js` code located on line 124.
For customizer go and find `customizer.php` in 'inc' folder. Go line 53 and change `js/customizer.js` code to `assets/js/customizer.js`
Don't forget to move your files :) |
289,556 | <p>I have id of WP category on external resource.
I know that if I have id of post I can create url like</p>
<blockquote>
<p><a href="http://example.com/?p=" rel="nofollow noreferrer">http://example.com/?p=</a>{post_id}</p>
</blockquote>
<p>But what if I know id of category? How can I generate link to it?
Category permalinks look like</p>
<blockquote>
<p><a href="http://example.com/category/" rel="nofollow noreferrer">http://example.com/category/</a>{category_slug}/</p>
</blockquote>
<p>and I need to use something like</p>
<blockquote>
<p><a href="http://example.com/category/?cat_id=" rel="nofollow noreferrer">http://example.com/category/?cat_id=</a>{category_id}/</p>
</blockquote>
| [
{
"answer_id": 289557,
"author": "janh",
"author_id": 129206,
"author_profile": "https://wordpress.stackexchange.com/users/129206",
"pm_score": 1,
"selected": false,
"text": "<p>use <a href=\"https://developer.wordpress.org/reference/functions/get_term_link/\" rel=\"nofollow noreferrer\">get_term_link</a>:</p>\n\n<pre><code>print get_term_link( $category_id, $taxonomy );\n</code></pre>\n"
},
{
"answer_id": 289568,
"author": "jas",
"author_id": 80247,
"author_profile": "https://wordpress.stackexchange.com/users/80247",
"pm_score": 3,
"selected": true,
"text": "<p>If you have category ID you can create link to category like below : </p>\n\n<pre><code><a href=\"/index.php?cat=7\">Category Title</a>\n</code></pre>\n\n<p>For more details read from this link : </p>\n\n<p><a href=\"https://codex.wordpress.org/Linking_Posts_Pages_and_Categories\" rel=\"nofollow noreferrer\">https://codex.wordpress.org/Linking_Posts_Pages_and_Categories</a></p>\n\n<p>Thanks!</p>\n"
},
{
"answer_id": 358973,
"author": "Rajeev",
"author_id": 177282,
"author_profile": "https://wordpress.stackexchange.com/users/177282",
"pm_score": 1,
"selected": false,
"text": "<p>If you have the category id then you can easily get the category URL using the below code.</p>\n\n<pre><code>get_category_link( $category_id );\n</code></pre>\n\n<p><strong><em>Example:</em></strong></p>\n\n<pre><code><a href=\"<?php echo esc_url( get_category_link( $category_id) ); ?>\" class=\"view_more_button\">View More</a>\n</code></pre>\n"
}
]
| 2017/12/27 | [
"https://wordpress.stackexchange.com/questions/289556",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/16650/"
]
| I have id of WP category on external resource.
I know that if I have id of post I can create url like
>
> <http://example.com/?p=>{post\_id}
>
>
>
But what if I know id of category? How can I generate link to it?
Category permalinks look like
>
> <http://example.com/category/>{category\_slug}/
>
>
>
and I need to use something like
>
> <http://example.com/category/?cat_id=>{category\_id}/
>
>
> | If you have category ID you can create link to category like below :
```
<a href="/index.php?cat=7">Category Title</a>
```
For more details read from this link :
<https://codex.wordpress.org/Linking_Posts_Pages_and_Categories>
Thanks! |
289,558 | <p>I have recently enabled SSL certificate and I'm tring to use it in my wordpress site. My website's url is </p>
<hr>
<p>All plugings are disabled.</p>
<hr>
<p>I replaced </p>
<pre><code> define('WP_HOME','http://mywebsite.com');
define('WP_SITEURL','http://mywebsite.com');
</code></pre>
<p>with:</p>
<pre><code>define('WP_HOME','https://mywebsite.com');
define('WP_SITEURL','https://mywebsite.com');
</code></pre>
<hr>
<p>Here's what I get in <a href="http://www.redirect-checker.org" rel="nofollow noreferrer">http://www.redirect-checker.org</a>:</p>
<blockquote>
<p>301 Moved Permanently <a href="https://mywebsite.com/" rel="nofollow noreferrer">https://mywebsite.com/</a> 301 Moved Permanently
<a href="https://mywebsite.com/" rel="nofollow noreferrer">https://mywebsite.com/</a> 301 Moved Permanently <a href="https://mywebsite.com/" rel="nofollow noreferrer">https://mywebsite.com/</a> 301
Moved Permanently</p>
<p>Problems found: Too many redirects. Please try to reduce your number
of redirects for <a href="https://mywebsite.com" rel="nofollow noreferrer">https://mywebsite.com</a>. Actually you use 19 Redirects.
Ideally you should not use more than 3 Redirects in a redirect chain.
More than 3 redirections will produce unnecessary load on your server
and reduces speed, which ends up in bad user experience.</p>
</blockquote>
<hr>
<p>A simple .txt file is working ok with https. For example:</p>
<p><strong><a href="https://mywebsite.com/license.txt" rel="nofollow noreferrer">https://mywebsite.com/license.txt</a></strong></p>
<p>gives "200 OK" message and page is browsed via https normally.</p>
<p>But trying to browse .index.php (which includes wordpress) is giving "too many redirects" error.</p>
<hr>
<p>I tried adding redirects to .htacess file but didn't work. I have read many articles about this issu but haven't managed to solve it. Can you help me please?</p>
<hr>
<p>UPDATE</p>
<p>Here are the _SERVER variables, shown by phpinfo()</p>
<pre><code>_SERVER["UNIQUE_ID"] WkOCLwoADAIAAFpxjJQAAAAG
_SERVER["QS_SrvConn"] 290
_SERVER["QS_AllConn"] 290
_SERVER["QS_ConnectionId"] 15143736798377620623491
_SERVER["HTTPS"] 1
_SERVER["HOME"] /home10a/sub002/sc11808-TCBG
_SERVER["HTTP_HOST"] mywebsite.com
_SERVER["HTTP_USER_AGENT"] Mozilla/5.0 (Windows NT 6.1; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/63.0.3239.84 Safari/537.36
_SERVER["HTTP_UPGRADE_INSECURE_REQUESTS"] 1
_SERVER["HTTP_ACCEPT"] text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,image/apng,*/*;q=0.8
_SERVER["HTTP_ACCEPT_ENCODING"] gzip, deflate, br
_SERVER["HTTP_ACCEPT_LANGUAGE"] en-US,en;q=0.9,el;q=0.8
_SERVER["HTTP_COOKIE"] wordpress_test_cookie=WP+Cookie+check; wordpress_logged_in_dbdaedf581c00cfca1e0c4de7c421d21=marketing%7C1514545975%7C91BD7fgU1i2AZl6rYQQ1cjIFfYkG2raYJp0VNXAIEHM%7C9a9f559abd4e30c57834d12a093683a1b6ff5dff14fbbf341983e1acee2fef58; wp-settings-3=mfold%3Do%26editor%3Dtinymce%26libraryContent%3Dbrowse%26galleryitemtype_tab%3Dpop%26hidetb%3D1%26wplink%3D0%26posts_list_mode%3Dlist%26imgsize%3Dfull; wp-settings-time-3=1514373177; redux_blast=1514373287; PHPSESSID=568be9d8e51767786dfc80915ff881a3; redux_update_check=3.6.7.13
_SERVER["HTTP_SSL"] on
_SERVER["HTTP_X_FORWARDED_FOR"] 78.108.43.18
_SERVER["HTTP_X_FORWARDED_HOST"] mywebsite.com
_SERVER["HTTP_X_FORWARDED_SERVER"] mywebsite.com
_SERVER["PATH"] /usr/local/bin:/usr/bin:/bin
_SERVER["SERVER_SIGNATURE"] <address>Apache Server at mywebsite.com Port 80</address>
_SERVER["SERVER_SOFTWARE"] Apache
_SERVER["SERVER_NAME"] mywebsite.com
_SERVER["SERVER_ADDR"] 10.0.12.2
_SERVER["SERVER_PORT"] 80
_SERVER["REMOTE_ADDR"] 77.232.66.255
_SERVER["DOCUMENT_ROOT"] /home10a/sub002/sc11808-TCBG/www
_SERVER["SERVER_ADMIN"] [no address given]
_SERVER["SCRIPT_FILENAME"] /home10a/sub002/sc11808-TCBG/www/info.php
_SERVER["REMOTE_PORT"] 45245
_SERVER["GATEWAY_INTERFACE"] CGI/1.1
_SERVER["SERVER_PROTOCOL"] HTTP/1.0
_SERVER["REQUEST_METHOD"] GET
_SERVER["QUERY_STRING"] no value
_SERVER["REQUEST_URI"] /info.php
_SERVER["SCRIPT_NAME"] /info.php
_SERVER["PHP_SELF"] /info.php
_SERVER["REQUEST_TIME"] 1514373679
</code></pre>
<hr>
| [
{
"answer_id": 289557,
"author": "janh",
"author_id": 129206,
"author_profile": "https://wordpress.stackexchange.com/users/129206",
"pm_score": 1,
"selected": false,
"text": "<p>use <a href=\"https://developer.wordpress.org/reference/functions/get_term_link/\" rel=\"nofollow noreferrer\">get_term_link</a>:</p>\n\n<pre><code>print get_term_link( $category_id, $taxonomy );\n</code></pre>\n"
},
{
"answer_id": 289568,
"author": "jas",
"author_id": 80247,
"author_profile": "https://wordpress.stackexchange.com/users/80247",
"pm_score": 3,
"selected": true,
"text": "<p>If you have category ID you can create link to category like below : </p>\n\n<pre><code><a href=\"/index.php?cat=7\">Category Title</a>\n</code></pre>\n\n<p>For more details read from this link : </p>\n\n<p><a href=\"https://codex.wordpress.org/Linking_Posts_Pages_and_Categories\" rel=\"nofollow noreferrer\">https://codex.wordpress.org/Linking_Posts_Pages_and_Categories</a></p>\n\n<p>Thanks!</p>\n"
},
{
"answer_id": 358973,
"author": "Rajeev",
"author_id": 177282,
"author_profile": "https://wordpress.stackexchange.com/users/177282",
"pm_score": 1,
"selected": false,
"text": "<p>If you have the category id then you can easily get the category URL using the below code.</p>\n\n<pre><code>get_category_link( $category_id );\n</code></pre>\n\n<p><strong><em>Example:</em></strong></p>\n\n<pre><code><a href=\"<?php echo esc_url( get_category_link( $category_id) ); ?>\" class=\"view_more_button\">View More</a>\n</code></pre>\n"
}
]
| 2017/12/27 | [
"https://wordpress.stackexchange.com/questions/289558",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/16847/"
]
| I have recently enabled SSL certificate and I'm tring to use it in my wordpress site. My website's url is
---
All plugings are disabled.
---
I replaced
```
define('WP_HOME','http://mywebsite.com');
define('WP_SITEURL','http://mywebsite.com');
```
with:
```
define('WP_HOME','https://mywebsite.com');
define('WP_SITEURL','https://mywebsite.com');
```
---
Here's what I get in <http://www.redirect-checker.org>:
>
> 301 Moved Permanently <https://mywebsite.com/> 301 Moved Permanently
> <https://mywebsite.com/> 301 Moved Permanently <https://mywebsite.com/> 301
> Moved Permanently
>
>
> Problems found: Too many redirects. Please try to reduce your number
> of redirects for <https://mywebsite.com>. Actually you use 19 Redirects.
> Ideally you should not use more than 3 Redirects in a redirect chain.
> More than 3 redirections will produce unnecessary load on your server
> and reduces speed, which ends up in bad user experience.
>
>
>
---
A simple .txt file is working ok with https. For example:
**<https://mywebsite.com/license.txt>**
gives "200 OK" message and page is browsed via https normally.
But trying to browse .index.php (which includes wordpress) is giving "too many redirects" error.
---
I tried adding redirects to .htacess file but didn't work. I have read many articles about this issu but haven't managed to solve it. Can you help me please?
---
UPDATE
Here are the \_SERVER variables, shown by phpinfo()
```
_SERVER["UNIQUE_ID"] WkOCLwoADAIAAFpxjJQAAAAG
_SERVER["QS_SrvConn"] 290
_SERVER["QS_AllConn"] 290
_SERVER["QS_ConnectionId"] 15143736798377620623491
_SERVER["HTTPS"] 1
_SERVER["HOME"] /home10a/sub002/sc11808-TCBG
_SERVER["HTTP_HOST"] mywebsite.com
_SERVER["HTTP_USER_AGENT"] Mozilla/5.0 (Windows NT 6.1; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/63.0.3239.84 Safari/537.36
_SERVER["HTTP_UPGRADE_INSECURE_REQUESTS"] 1
_SERVER["HTTP_ACCEPT"] text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,image/apng,*/*;q=0.8
_SERVER["HTTP_ACCEPT_ENCODING"] gzip, deflate, br
_SERVER["HTTP_ACCEPT_LANGUAGE"] en-US,en;q=0.9,el;q=0.8
_SERVER["HTTP_COOKIE"] wordpress_test_cookie=WP+Cookie+check; wordpress_logged_in_dbdaedf581c00cfca1e0c4de7c421d21=marketing%7C1514545975%7C91BD7fgU1i2AZl6rYQQ1cjIFfYkG2raYJp0VNXAIEHM%7C9a9f559abd4e30c57834d12a093683a1b6ff5dff14fbbf341983e1acee2fef58; wp-settings-3=mfold%3Do%26editor%3Dtinymce%26libraryContent%3Dbrowse%26galleryitemtype_tab%3Dpop%26hidetb%3D1%26wplink%3D0%26posts_list_mode%3Dlist%26imgsize%3Dfull; wp-settings-time-3=1514373177; redux_blast=1514373287; PHPSESSID=568be9d8e51767786dfc80915ff881a3; redux_update_check=3.6.7.13
_SERVER["HTTP_SSL"] on
_SERVER["HTTP_X_FORWARDED_FOR"] 78.108.43.18
_SERVER["HTTP_X_FORWARDED_HOST"] mywebsite.com
_SERVER["HTTP_X_FORWARDED_SERVER"] mywebsite.com
_SERVER["PATH"] /usr/local/bin:/usr/bin:/bin
_SERVER["SERVER_SIGNATURE"] <address>Apache Server at mywebsite.com Port 80</address>
_SERVER["SERVER_SOFTWARE"] Apache
_SERVER["SERVER_NAME"] mywebsite.com
_SERVER["SERVER_ADDR"] 10.0.12.2
_SERVER["SERVER_PORT"] 80
_SERVER["REMOTE_ADDR"] 77.232.66.255
_SERVER["DOCUMENT_ROOT"] /home10a/sub002/sc11808-TCBG/www
_SERVER["SERVER_ADMIN"] [no address given]
_SERVER["SCRIPT_FILENAME"] /home10a/sub002/sc11808-TCBG/www/info.php
_SERVER["REMOTE_PORT"] 45245
_SERVER["GATEWAY_INTERFACE"] CGI/1.1
_SERVER["SERVER_PROTOCOL"] HTTP/1.0
_SERVER["REQUEST_METHOD"] GET
_SERVER["QUERY_STRING"] no value
_SERVER["REQUEST_URI"] /info.php
_SERVER["SCRIPT_NAME"] /info.php
_SERVER["PHP_SELF"] /info.php
_SERVER["REQUEST_TIME"] 1514373679
```
--- | If you have category ID you can create link to category like below :
```
<a href="/index.php?cat=7">Category Title</a>
```
For more details read from this link :
<https://codex.wordpress.org/Linking_Posts_Pages_and_Categories>
Thanks! |
289,574 | <p>This is my entire code and it is working perfectly in my local system xampp but not working on server.</p>
<pre><code>function taqyeem_dequeue_scrips() {
if(basename($_SERVER['REQUEST_URI'])=='my_page' || basename($_SERVER['REQUEST_URI'])=='')
{
wp_dequeue_style( 'taqyeem-style' );
wp_dequeue_script( 'taqyeem-main' );
wp_deregister_script( 'comment-reply' );
}
}
add_action( 'init', 'taqyeem_dequeue_scrips' );
function dequeue_scrips() {
if(basename($_SERVER['REQUEST_URI'])=='my_page')
{
//css
wp_dequeue_style( 'taxonomy-image-plugin-public' );
wp_dequeue_style( 'job-alerts-frontend' );
wp_dequeue_style('validate-engine-css');
wp_dequeue_style('cp-shortcode');
wp_dequeue_style('wsl-widget');
wp_dequeue_style('wp-job-manager-applications-frontend');
wp_dequeue_style('wp-job-manager-bookmarks-frontend');
wp_dequeue_style('wp-job-manager-resume-frontend');
wp_dequeue_style('wp-job-manager-frontend');
wp_dequeue_style('cp-widgets-css');
wp_dequeue_style('responsive-css');
wp_dequeue_style('owl-css');
wp_dequeue_style('svg-css');
wp_dequeue_style('cp-burgermenucss');
wp_dequeue_style('law-bx-slider-css');
wp_dequeue_style('prettyPhoto');
wp_dequeue_style('cp-bootstrap');
wp_dequeue_style('cp-wp-commerce');
wp_dequeue_style('cp-bx-slider');
wp_dequeue_style('googleFonts');
wp_dequeue_style('googleFonts-heading');
wp_dequeue_style('menu-googleFonts-heading');
wp_dequeue_style('wppb_stylesheet');
wp_dequeue_style('A2A_SHARE_SAVE');
//Script
wp_dequeue_script( 'html5shiv' );
wp_dequeue_script( 'cp-bootstrap' );
wp_dequeue_script( 'addtoany' );
wp_dequeue_script( 'cp-owl-js' );
wp_dequeue_script( 'cp-velocity' );
wp_dequeue_script( 'owl-kenburns' );
wp_dequeue_script( 'cp-burgermenu' );
wp_dequeue_script( 'cp-burgermenucustom' );
wp_dequeue_script( 'cp-bx-slider' );
wp_dequeue_script( 'cp-custom' );
wp_dequeue_script( 'prettyPhoto' );
wp_dequeue_script( 'cp-pscript' );
wp_dequeue_script( 'cp-scripts_modernizr' );
wp_dequeue_script( 'cp-scripts' );
wp_dequeue_script( 'cp-scripts-workmark' );
wp_dequeue_script( 'cp-easing' );
wp_dequeue_script( 'cp-bx-slider' );
}
}
add_action( 'wp_enqueue_scripts', 'dequeue_scrips' );
</code></pre>
<p>Any suggestion please. I am working to improve Google Page Speed to get atleast 90 score in mobile and desktop. Currently itis poor in mobile (56 )</p>
| [
{
"answer_id": 289557,
"author": "janh",
"author_id": 129206,
"author_profile": "https://wordpress.stackexchange.com/users/129206",
"pm_score": 1,
"selected": false,
"text": "<p>use <a href=\"https://developer.wordpress.org/reference/functions/get_term_link/\" rel=\"nofollow noreferrer\">get_term_link</a>:</p>\n\n<pre><code>print get_term_link( $category_id, $taxonomy );\n</code></pre>\n"
},
{
"answer_id": 289568,
"author": "jas",
"author_id": 80247,
"author_profile": "https://wordpress.stackexchange.com/users/80247",
"pm_score": 3,
"selected": true,
"text": "<p>If you have category ID you can create link to category like below : </p>\n\n<pre><code><a href=\"/index.php?cat=7\">Category Title</a>\n</code></pre>\n\n<p>For more details read from this link : </p>\n\n<p><a href=\"https://codex.wordpress.org/Linking_Posts_Pages_and_Categories\" rel=\"nofollow noreferrer\">https://codex.wordpress.org/Linking_Posts_Pages_and_Categories</a></p>\n\n<p>Thanks!</p>\n"
},
{
"answer_id": 358973,
"author": "Rajeev",
"author_id": 177282,
"author_profile": "https://wordpress.stackexchange.com/users/177282",
"pm_score": 1,
"selected": false,
"text": "<p>If you have the category id then you can easily get the category URL using the below code.</p>\n\n<pre><code>get_category_link( $category_id );\n</code></pre>\n\n<p><strong><em>Example:</em></strong></p>\n\n<pre><code><a href=\"<?php echo esc_url( get_category_link( $category_id) ); ?>\" class=\"view_more_button\">View More</a>\n</code></pre>\n"
}
]
| 2017/12/27 | [
"https://wordpress.stackexchange.com/questions/289574",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/70096/"
]
| This is my entire code and it is working perfectly in my local system xampp but not working on server.
```
function taqyeem_dequeue_scrips() {
if(basename($_SERVER['REQUEST_URI'])=='my_page' || basename($_SERVER['REQUEST_URI'])=='')
{
wp_dequeue_style( 'taqyeem-style' );
wp_dequeue_script( 'taqyeem-main' );
wp_deregister_script( 'comment-reply' );
}
}
add_action( 'init', 'taqyeem_dequeue_scrips' );
function dequeue_scrips() {
if(basename($_SERVER['REQUEST_URI'])=='my_page')
{
//css
wp_dequeue_style( 'taxonomy-image-plugin-public' );
wp_dequeue_style( 'job-alerts-frontend' );
wp_dequeue_style('validate-engine-css');
wp_dequeue_style('cp-shortcode');
wp_dequeue_style('wsl-widget');
wp_dequeue_style('wp-job-manager-applications-frontend');
wp_dequeue_style('wp-job-manager-bookmarks-frontend');
wp_dequeue_style('wp-job-manager-resume-frontend');
wp_dequeue_style('wp-job-manager-frontend');
wp_dequeue_style('cp-widgets-css');
wp_dequeue_style('responsive-css');
wp_dequeue_style('owl-css');
wp_dequeue_style('svg-css');
wp_dequeue_style('cp-burgermenucss');
wp_dequeue_style('law-bx-slider-css');
wp_dequeue_style('prettyPhoto');
wp_dequeue_style('cp-bootstrap');
wp_dequeue_style('cp-wp-commerce');
wp_dequeue_style('cp-bx-slider');
wp_dequeue_style('googleFonts');
wp_dequeue_style('googleFonts-heading');
wp_dequeue_style('menu-googleFonts-heading');
wp_dequeue_style('wppb_stylesheet');
wp_dequeue_style('A2A_SHARE_SAVE');
//Script
wp_dequeue_script( 'html5shiv' );
wp_dequeue_script( 'cp-bootstrap' );
wp_dequeue_script( 'addtoany' );
wp_dequeue_script( 'cp-owl-js' );
wp_dequeue_script( 'cp-velocity' );
wp_dequeue_script( 'owl-kenburns' );
wp_dequeue_script( 'cp-burgermenu' );
wp_dequeue_script( 'cp-burgermenucustom' );
wp_dequeue_script( 'cp-bx-slider' );
wp_dequeue_script( 'cp-custom' );
wp_dequeue_script( 'prettyPhoto' );
wp_dequeue_script( 'cp-pscript' );
wp_dequeue_script( 'cp-scripts_modernizr' );
wp_dequeue_script( 'cp-scripts' );
wp_dequeue_script( 'cp-scripts-workmark' );
wp_dequeue_script( 'cp-easing' );
wp_dequeue_script( 'cp-bx-slider' );
}
}
add_action( 'wp_enqueue_scripts', 'dequeue_scrips' );
```
Any suggestion please. I am working to improve Google Page Speed to get atleast 90 score in mobile and desktop. Currently itis poor in mobile (56 ) | If you have category ID you can create link to category like below :
```
<a href="/index.php?cat=7">Category Title</a>
```
For more details read from this link :
<https://codex.wordpress.org/Linking_Posts_Pages_and_Categories>
Thanks! |
289,582 | <p>I need to remove trailing slash from URLs ending with <code>.xml/</code> only .. For this purpose I've created a Rewrite Condition and Rule which is working perfectly fine for the test link <a href="http://website.com/test.xml/" rel="nofollow noreferrer">http://website.com/test.xml/</a></p>
<p>Test Link: <a href="http://htaccess.mwl.be?share=6fe08232-438a-53fa-8f1a-1f7f69b77b6f" rel="nofollow noreferrer">http://htaccess.mwl.be?share=6fe08232-438a-53fa-8f1a-1f7f69b77b6f</a></p>
<p>The problem is when I place the rule in WordPress <code>.htaccess</code> file, it doesn't work at all! Seems like WordPress or YOAST Permalink structure is overriding the rule .. please help!</p>
<pre><code># BEGIN WordPress
<IfModule mod_rewrite.c>
RewriteEngine On
RewriteBase /
RewriteRule ^index\.php$ - [L]
RewriteCond %{REQUEST_URI} /(.*).xml/$
RewriteRule ^ /%1.xml [L]
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule . /index.php [L]
</IfModule>
# END WordPress
</code></pre>
<p>Note:</p>
<p>Please note that this is not a physical file .. using rewrite rules to generate sitemap on the run! This is a wordpress page in fact!</p>
<p><code>add_rewrite_rule('([^/]*)-placeholder.xml','index.php?page_id=123&customββ-slug=$matches[1]','ββtop');</code></p>
| [
{
"answer_id": 289588,
"author": "MrWhite",
"author_id": 8259,
"author_profile": "https://wordpress.stackexchange.com/users/8259",
"pm_score": 1,
"selected": false,
"text": "<blockquote>\n<pre><code>RewriteRule ^ /%1.xml [L]\n</code></pre>\n</blockquote>\n\n<p>This should be an <em>external redirect</em>, not an <em>internal rewrite</em>. (Otherwise it won't look like it's doing anything, as the visible URL won't change.) So, you need the <code>R</code> (<code>redirect</code>) flag. For example:</p>\n\n<pre><code> RewriteRule ^ /%1.xml [R,L]\n</code></pre>\n\n<p>This is a temporary (302) redirect. Change <code>R</code> to <code>R=301</code> to make it a permanent (301) redirect - but only when you are sure it's working OK. (Since 301s are cached hard by the browser and can make testing problematic.)</p>\n\n<p>However, you don't need the <code>RewriteCond</code> directive. This can be done in a single <code>RewriteRule</code> (it will also be more efficient to do so). This should also go <em>before</em> your existing <em>internal rewrites</em> and ideally <em>before</em> the <code># BEGIN WordPress</code> block, as otherwise your customisation could be overridden in future updates.</p>\n\n<p>So, all you need is (at the top of your file):</p>\n\n<pre><code>RewriteRule ^(.+)\\.xml/$ /$1.xml [R,L]\n</code></pre>\n\n<p>Remember to escape literal dots in your regex.</p>\n\n<p><strong>UPDATE:</strong> And yes, that should be <code>$1</code> (as a backreference to the <code>RewriteRule</code> <em>pattern</em>) as opposed to <code>%1</code> (a backreference to the last matched <em>CondPattern</em>).</p>\n"
},
{
"answer_id": 289609,
"author": "Milo",
"author_id": 4771,
"author_profile": "https://wordpress.stackexchange.com/users/4771",
"pm_score": 2,
"selected": false,
"text": "<p>If you're outputting a sitemap, there's no reason to wait for the query for your page- which is what is producing the redirect.</p>\n\n<p>Hook an earlier action and you won't need anything to counter the trailing slash, because it won't happen-</p>\n\n<p><strong>EDIT</strong></p>\n\n<p>Here's a complete version with registering query vars, rules, and <code>parse_request</code> action:</p>\n\n<pre><code>// add the custom query vars\n// WordPress will not parse query vars in rules\n// if they are not added to the list of valid query vars\nfunction wpd_sitemap_query_var( $vars ){\n $vars[] = 'svc-slug';\n $vars[] = 'svc-offset';\n return $vars;\n}\nadd_filter( 'query_vars', 'wpd_sitemap_query_var' );\n\n// add the rules\nfunction wpd_sitemap_rewrite_rules() {\n add_rewrite_rule(\n '([^/]*)-svc-([0-9]+).xml',\n 'index.php?page_id='.get_field('dynamic_sitemap','option').'&svc-slug=$matches[1]&svc-offset=$matches[2]',\n 'top'\n );\n add_rewrite_rule(\n '([^/]*)-svc.xml',\n 'index.php?page_id='.get_field('dynamic_sitemap','option').'&svc-slug=$matches[1]',\n 'top'\n );\n}\nadd_action('init', 'wpd_sitemap_rewrite_rules', 10, 0);\n\n// intercept the query and test if our query var is set\n// this means one of our rules matched and we should show the sitemap\nfunction wpd_sitemap_parse_request( $query ){\n if( isset( $query->query_vars['svc-slug'] ) ){\n echo '<pre>';\n print_r( $query->query_vars );\n echo '</pre>';\n\n // halt further execution after sitemap is output\n die;\n }\n}\nadd_action( 'parse_request', 'wpd_sitemap_parse_request' );\n</code></pre>\n"
},
{
"answer_id": 290112,
"author": "Hassan Alvi",
"author_id": 58627,
"author_profile": "https://wordpress.stackexchange.com/users/58627",
"pm_score": 1,
"selected": true,
"text": "<p>What exactly worked out for me ..</p>\n\n<p>The issue was due to WordPress canonical redirects .. The use of <code>/%postname%/</code> in permalink structure was redirecting the custom template to the trailing slash URL.</p>\n\n<p>I simply removed the <code>template_redirect</code> filter for canonical redirects .. and now the link works in both cases i.e. with or without trailing slash.</p>\n\n<p>Here is my code for reference.. 1234 is the example page id for the template used to generate dynamic sitemap.</p>\n\n<p><code>//Disabling canonical redirects for sitemap\nfunction disable_sitemap_redirect() {\n global $wp;\n $current_url = home_url(add_query_arg(array(),$wp->request));\n $current_url = $current_url . $_SERVER['REDIRECT_URL'];\n $id = url_to_postid($current_url);\n if($id == 1234) : remove_filter('template_redirect', 'redirect_canonical'); endif;\n}\nadd_action('init', 'disable_sitemap_redirect', 10, 0);</code></p>\n"
}
]
| 2017/12/27 | [
"https://wordpress.stackexchange.com/questions/289582",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/58627/"
]
| I need to remove trailing slash from URLs ending with `.xml/` only .. For this purpose I've created a Rewrite Condition and Rule which is working perfectly fine for the test link <http://website.com/test.xml/>
Test Link: <http://htaccess.mwl.be?share=6fe08232-438a-53fa-8f1a-1f7f69b77b6f>
The problem is when I place the rule in WordPress `.htaccess` file, it doesn't work at all! Seems like WordPress or YOAST Permalink structure is overriding the rule .. please help!
```
# BEGIN WordPress
<IfModule mod_rewrite.c>
RewriteEngine On
RewriteBase /
RewriteRule ^index\.php$ - [L]
RewriteCond %{REQUEST_URI} /(.*).xml/$
RewriteRule ^ /%1.xml [L]
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule . /index.php [L]
</IfModule>
# END WordPress
```
Note:
Please note that this is not a physical file .. using rewrite rules to generate sitemap on the run! This is a wordpress page in fact!
`add_rewrite_rule('([^/]*)-placeholder.xml','index.php?page_id=123&customββ-slug=$matches[1]','ββtop');` | What exactly worked out for me ..
The issue was due to WordPress canonical redirects .. The use of `/%postname%/` in permalink structure was redirecting the custom template to the trailing slash URL.
I simply removed the `template_redirect` filter for canonical redirects .. and now the link works in both cases i.e. with or without trailing slash.
Here is my code for reference.. 1234 is the example page id for the template used to generate dynamic sitemap.
`//Disabling canonical redirects for sitemap
function disable_sitemap_redirect() {
global $wp;
$current_url = home_url(add_query_arg(array(),$wp->request));
$current_url = $current_url . $_SERVER['REDIRECT_URL'];
$id = url_to_postid($current_url);
if($id == 1234) : remove_filter('template_redirect', 'redirect_canonical'); endif;
}
add_action('init', 'disable_sitemap_redirect', 10, 0);` |
289,590 | <p>im new with wordpress. im planning to connect wordpress database from my own php code . but i get problem when trying to connect database, everytime i connect always get error result. im using this code</p>
<pre><code>$user_name = "myusername";
$password = "password";
$database = "mydatabasename";
$host_name = "localhost";
$connect_db=mysqli_connect($host_name, $user_name, $password);
$find_db=mysqli_select_db($database);
if ($find_db) {
echo "Database found";
mysqli_close($connect_db);
}
else {
echo "Database notfound";
mysqli_close($connect_db);
}
</code></pre>
| [
{
"answer_id": 289594,
"author": "D. Dan",
"author_id": 133528,
"author_profile": "https://wordpress.stackexchange.com/users/133528",
"pm_score": 0,
"selected": false,
"text": "<p>Try using <a href=\"https://codex.wordpress.org/Class_Reference/wpdb\" rel=\"nofollow noreferrer\">wpdb</a>. It's the built in class for handling external databases.</p>\n"
},
{
"answer_id": 289595,
"author": "Nefro",
"author_id": 86801,
"author_profile": "https://wordpress.stackexchange.com/users/86801",
"pm_score": 0,
"selected": false,
"text": "<p>Maybe you don't need connect to database but implement wordpress functions on custom code ? </p>\n\n<p>Just include wp-config.php file on custom code and you can use all wordpress functions.</p>\n\n<pre><code><?php\n\nrequire_once('wp-config.php');\n\n$posts = new WP_Query(...);\n</code></pre>\n\n<p>after that you can use wordpress <a href=\"https://codex.wordpress.org/Class_Reference/wpdb\" rel=\"nofollow noreferrer\">wpdb</a> class</p>\n\n<pre><code>$myrows = $wpdb->get_results( \"SELECT id, name FROM mytable\" );\n</code></pre>\n"
},
{
"answer_id": 289598,
"author": "Waleed Asender",
"author_id": 44821,
"author_profile": "https://wordpress.stackexchange.com/users/44821",
"pm_score": 0,
"selected": false,
"text": "<p>No need to do custom mysql connection, you can include wp-blog-header.php file and get all wp functionality working in your PHP file:</p>\n\n<pre><code><?php require 'PATH-TO-WP/wp-blog-header.php'; ?>\n</code></pre>\n"
},
{
"answer_id": 289608,
"author": "Clinton",
"author_id": 122375,
"author_profile": "https://wordpress.stackexchange.com/users/122375",
"pm_score": 1,
"selected": false,
"text": "<p>While it may possible to connect using mysqli->connect it is always better to make use of built in Wordpress functionality (even for external code).</p>\n\n<p>By this I mean that you should use the wpdb class. See <a href=\"https://codex.wordpress.org/Class_Reference/wpdb\" rel=\"nofollow noreferrer\">https://codex.wordpress.org/Class_Reference/wpdb</a> for more information.</p>\n\n<p>First you need to link to the Wordpress class:</p>\n\n<pre><code>echo '<h1>WP Connect DB</h1>';\necho '<p>Directory Check: '.$_SERVER['DOCUMENT_ROOT'] . '/wp-load.php</p>';\nrequire_once( $_SERVER['DOCUMENT_ROOT'] . '/wp-load.php' );\n</code></pre>\n\n<p>If you get an error, check that the path to wp-load is correct and adjust if necessary.</p>\n\n<p>Next you can define the user and database etc.</p>\n\n<pre><code>/** The name of the database for WordPress */\ndefine('DB_NAME', 'mydatabase');\n/** MySQL database username */\ndefine('DB_USER', 'myusername');\n/** MySQL database password */\ndefine('DB_PASSWORD', 'mypassword');\n/** MySQL hostname */\ndefine('DB_HOST', 'localhost');\n</code></pre>\n\n<p>This info comes straight from the wp-config.php file. These do not need to be defined as constants, you can submit these directly into the right place in the database connection code below:</p>\n\n<pre><code>$wpdb = new wpdb( DB_USER, DB_PASSWORD, DB_NAME, DB_HOST);\n</code></pre>\n\n<p>Finally you can do something with the results for example:</p>\n\n<pre><code>$rows = $wpdb->get_results( \"SELECT * FROM wp_posts\" );\necho '<h3>Results</h3><pre>'.var_export($rows,true).'</pre>';\n</code></pre>\n\n<p>Putting it all together your code would look like this:</p>\n\n<pre><code>echo '<h1>WP Connect DB</h1>';\necho '<p>Directory: '.$_SERVER['DOCUMENT_ROOT'] . '/wpdev/wp-load.php</p>';\nrequire_once( $_SERVER['DOCUMENT_ROOT'] . '/wpdev/wp-load.php' );\ndefine('SHORTINIT', true );\n/** The name of the database for WordPress */\ndefine('DB_NAME', 'mydatabase');\n/** MySQL database username */\ndefine('DB_USER', 'myusername');\n/** MySQL database password */\ndefine('DB_PASSWORD', 'mypassword');\n/** MySQL hostname */\ndefine('DB_HOST', 'localhost');\n$wpdb = new wpdb( DB_USER, DB_PASSWORD, DB_NAME, DB_HOST);\n$rows = $wpdb->get_results( \"SELECT * FROM wp_posts\" );\necho '<h3>Results</h3><pre>'.var_export($rows,true).'</pre>';\n</code></pre>\n\n<p>The additional SHORTINIT definition is added to minimise the Wordpress load but is not required.</p>\n\n<p>I hope that this helps.</p>\n"
}
]
| 2017/12/27 | [
"https://wordpress.stackexchange.com/questions/289590",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/133890/"
]
| im new with wordpress. im planning to connect wordpress database from my own php code . but i get problem when trying to connect database, everytime i connect always get error result. im using this code
```
$user_name = "myusername";
$password = "password";
$database = "mydatabasename";
$host_name = "localhost";
$connect_db=mysqli_connect($host_name, $user_name, $password);
$find_db=mysqli_select_db($database);
if ($find_db) {
echo "Database found";
mysqli_close($connect_db);
}
else {
echo "Database notfound";
mysqli_close($connect_db);
}
``` | While it may possible to connect using mysqli->connect it is always better to make use of built in Wordpress functionality (even for external code).
By this I mean that you should use the wpdb class. See <https://codex.wordpress.org/Class_Reference/wpdb> for more information.
First you need to link to the Wordpress class:
```
echo '<h1>WP Connect DB</h1>';
echo '<p>Directory Check: '.$_SERVER['DOCUMENT_ROOT'] . '/wp-load.php</p>';
require_once( $_SERVER['DOCUMENT_ROOT'] . '/wp-load.php' );
```
If you get an error, check that the path to wp-load is correct and adjust if necessary.
Next you can define the user and database etc.
```
/** The name of the database for WordPress */
define('DB_NAME', 'mydatabase');
/** MySQL database username */
define('DB_USER', 'myusername');
/** MySQL database password */
define('DB_PASSWORD', 'mypassword');
/** MySQL hostname */
define('DB_HOST', 'localhost');
```
This info comes straight from the wp-config.php file. These do not need to be defined as constants, you can submit these directly into the right place in the database connection code below:
```
$wpdb = new wpdb( DB_USER, DB_PASSWORD, DB_NAME, DB_HOST);
```
Finally you can do something with the results for example:
```
$rows = $wpdb->get_results( "SELECT * FROM wp_posts" );
echo '<h3>Results</h3><pre>'.var_export($rows,true).'</pre>';
```
Putting it all together your code would look like this:
```
echo '<h1>WP Connect DB</h1>';
echo '<p>Directory: '.$_SERVER['DOCUMENT_ROOT'] . '/wpdev/wp-load.php</p>';
require_once( $_SERVER['DOCUMENT_ROOT'] . '/wpdev/wp-load.php' );
define('SHORTINIT', true );
/** The name of the database for WordPress */
define('DB_NAME', 'mydatabase');
/** MySQL database username */
define('DB_USER', 'myusername');
/** MySQL database password */
define('DB_PASSWORD', 'mypassword');
/** MySQL hostname */
define('DB_HOST', 'localhost');
$wpdb = new wpdb( DB_USER, DB_PASSWORD, DB_NAME, DB_HOST);
$rows = $wpdb->get_results( "SELECT * FROM wp_posts" );
echo '<h3>Results</h3><pre>'.var_export($rows,true).'</pre>';
```
The additional SHORTINIT definition is added to minimise the Wordpress load but is not required.
I hope that this helps. |
289,600 | <p>Since I'm pretty new to WordPress, I would like to know what is the right way to edit the WP reset password email. I would like to change the message.</p>
<p>I see that I need to edit the <code>retrieve_password_message</code> filter but I cannot understand if I can change the <code>wp-login.php</code> file.</p>
<p>What will happen in case of WP update? Thanks</p>
| [
{
"answer_id": 289594,
"author": "D. Dan",
"author_id": 133528,
"author_profile": "https://wordpress.stackexchange.com/users/133528",
"pm_score": 0,
"selected": false,
"text": "<p>Try using <a href=\"https://codex.wordpress.org/Class_Reference/wpdb\" rel=\"nofollow noreferrer\">wpdb</a>. It's the built in class for handling external databases.</p>\n"
},
{
"answer_id": 289595,
"author": "Nefro",
"author_id": 86801,
"author_profile": "https://wordpress.stackexchange.com/users/86801",
"pm_score": 0,
"selected": false,
"text": "<p>Maybe you don't need connect to database but implement wordpress functions on custom code ? </p>\n\n<p>Just include wp-config.php file on custom code and you can use all wordpress functions.</p>\n\n<pre><code><?php\n\nrequire_once('wp-config.php');\n\n$posts = new WP_Query(...);\n</code></pre>\n\n<p>after that you can use wordpress <a href=\"https://codex.wordpress.org/Class_Reference/wpdb\" rel=\"nofollow noreferrer\">wpdb</a> class</p>\n\n<pre><code>$myrows = $wpdb->get_results( \"SELECT id, name FROM mytable\" );\n</code></pre>\n"
},
{
"answer_id": 289598,
"author": "Waleed Asender",
"author_id": 44821,
"author_profile": "https://wordpress.stackexchange.com/users/44821",
"pm_score": 0,
"selected": false,
"text": "<p>No need to do custom mysql connection, you can include wp-blog-header.php file and get all wp functionality working in your PHP file:</p>\n\n<pre><code><?php require 'PATH-TO-WP/wp-blog-header.php'; ?>\n</code></pre>\n"
},
{
"answer_id": 289608,
"author": "Clinton",
"author_id": 122375,
"author_profile": "https://wordpress.stackexchange.com/users/122375",
"pm_score": 1,
"selected": false,
"text": "<p>While it may possible to connect using mysqli->connect it is always better to make use of built in Wordpress functionality (even for external code).</p>\n\n<p>By this I mean that you should use the wpdb class. See <a href=\"https://codex.wordpress.org/Class_Reference/wpdb\" rel=\"nofollow noreferrer\">https://codex.wordpress.org/Class_Reference/wpdb</a> for more information.</p>\n\n<p>First you need to link to the Wordpress class:</p>\n\n<pre><code>echo '<h1>WP Connect DB</h1>';\necho '<p>Directory Check: '.$_SERVER['DOCUMENT_ROOT'] . '/wp-load.php</p>';\nrequire_once( $_SERVER['DOCUMENT_ROOT'] . '/wp-load.php' );\n</code></pre>\n\n<p>If you get an error, check that the path to wp-load is correct and adjust if necessary.</p>\n\n<p>Next you can define the user and database etc.</p>\n\n<pre><code>/** The name of the database for WordPress */\ndefine('DB_NAME', 'mydatabase');\n/** MySQL database username */\ndefine('DB_USER', 'myusername');\n/** MySQL database password */\ndefine('DB_PASSWORD', 'mypassword');\n/** MySQL hostname */\ndefine('DB_HOST', 'localhost');\n</code></pre>\n\n<p>This info comes straight from the wp-config.php file. These do not need to be defined as constants, you can submit these directly into the right place in the database connection code below:</p>\n\n<pre><code>$wpdb = new wpdb( DB_USER, DB_PASSWORD, DB_NAME, DB_HOST);\n</code></pre>\n\n<p>Finally you can do something with the results for example:</p>\n\n<pre><code>$rows = $wpdb->get_results( \"SELECT * FROM wp_posts\" );\necho '<h3>Results</h3><pre>'.var_export($rows,true).'</pre>';\n</code></pre>\n\n<p>Putting it all together your code would look like this:</p>\n\n<pre><code>echo '<h1>WP Connect DB</h1>';\necho '<p>Directory: '.$_SERVER['DOCUMENT_ROOT'] . '/wpdev/wp-load.php</p>';\nrequire_once( $_SERVER['DOCUMENT_ROOT'] . '/wpdev/wp-load.php' );\ndefine('SHORTINIT', true );\n/** The name of the database for WordPress */\ndefine('DB_NAME', 'mydatabase');\n/** MySQL database username */\ndefine('DB_USER', 'myusername');\n/** MySQL database password */\ndefine('DB_PASSWORD', 'mypassword');\n/** MySQL hostname */\ndefine('DB_HOST', 'localhost');\n$wpdb = new wpdb( DB_USER, DB_PASSWORD, DB_NAME, DB_HOST);\n$rows = $wpdb->get_results( \"SELECT * FROM wp_posts\" );\necho '<h3>Results</h3><pre>'.var_export($rows,true).'</pre>';\n</code></pre>\n\n<p>The additional SHORTINIT definition is added to minimise the Wordpress load but is not required.</p>\n\n<p>I hope that this helps.</p>\n"
}
]
| 2017/12/27 | [
"https://wordpress.stackexchange.com/questions/289600",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/133892/"
]
| Since I'm pretty new to WordPress, I would like to know what is the right way to edit the WP reset password email. I would like to change the message.
I see that I need to edit the `retrieve_password_message` filter but I cannot understand if I can change the `wp-login.php` file.
What will happen in case of WP update? Thanks | While it may possible to connect using mysqli->connect it is always better to make use of built in Wordpress functionality (even for external code).
By this I mean that you should use the wpdb class. See <https://codex.wordpress.org/Class_Reference/wpdb> for more information.
First you need to link to the Wordpress class:
```
echo '<h1>WP Connect DB</h1>';
echo '<p>Directory Check: '.$_SERVER['DOCUMENT_ROOT'] . '/wp-load.php</p>';
require_once( $_SERVER['DOCUMENT_ROOT'] . '/wp-load.php' );
```
If you get an error, check that the path to wp-load is correct and adjust if necessary.
Next you can define the user and database etc.
```
/** The name of the database for WordPress */
define('DB_NAME', 'mydatabase');
/** MySQL database username */
define('DB_USER', 'myusername');
/** MySQL database password */
define('DB_PASSWORD', 'mypassword');
/** MySQL hostname */
define('DB_HOST', 'localhost');
```
This info comes straight from the wp-config.php file. These do not need to be defined as constants, you can submit these directly into the right place in the database connection code below:
```
$wpdb = new wpdb( DB_USER, DB_PASSWORD, DB_NAME, DB_HOST);
```
Finally you can do something with the results for example:
```
$rows = $wpdb->get_results( "SELECT * FROM wp_posts" );
echo '<h3>Results</h3><pre>'.var_export($rows,true).'</pre>';
```
Putting it all together your code would look like this:
```
echo '<h1>WP Connect DB</h1>';
echo '<p>Directory: '.$_SERVER['DOCUMENT_ROOT'] . '/wpdev/wp-load.php</p>';
require_once( $_SERVER['DOCUMENT_ROOT'] . '/wpdev/wp-load.php' );
define('SHORTINIT', true );
/** The name of the database for WordPress */
define('DB_NAME', 'mydatabase');
/** MySQL database username */
define('DB_USER', 'myusername');
/** MySQL database password */
define('DB_PASSWORD', 'mypassword');
/** MySQL hostname */
define('DB_HOST', 'localhost');
$wpdb = new wpdb( DB_USER, DB_PASSWORD, DB_NAME, DB_HOST);
$rows = $wpdb->get_results( "SELECT * FROM wp_posts" );
echo '<h3>Results</h3><pre>'.var_export($rows,true).'</pre>';
```
The additional SHORTINIT definition is added to minimise the Wordpress load but is not required.
I hope that this helps. |
289,605 | <p>In my Ubuntu VPS, to search and replace in a DB of a site I do for example:</p>
<pre><code>cd /var/www/html/example.com
sudo wp search-replace "http://" "https://" --all-tables
</code></pre>
<p>Yet in Windows 10 I use XAMPP and can't do this action with WSL + WP-CLI because one cannot use Bash inside windows (yet).</p>
<h2>My problem</h2>
<p>I have installed a backup version of an online website in Windows XAMPP and all main menu links turn to the online site so I need to change in DB from <code>https://</code> to <code>localhost://</code>.</p>
<h2>My question</h2>
<p>How could I easily and efficiently change the DB from <code>https://</code> to <code>localhost://</code>. in XAMPP in Windows?</p>
| [
{
"answer_id": 289594,
"author": "D. Dan",
"author_id": 133528,
"author_profile": "https://wordpress.stackexchange.com/users/133528",
"pm_score": 0,
"selected": false,
"text": "<p>Try using <a href=\"https://codex.wordpress.org/Class_Reference/wpdb\" rel=\"nofollow noreferrer\">wpdb</a>. It's the built in class for handling external databases.</p>\n"
},
{
"answer_id": 289595,
"author": "Nefro",
"author_id": 86801,
"author_profile": "https://wordpress.stackexchange.com/users/86801",
"pm_score": 0,
"selected": false,
"text": "<p>Maybe you don't need connect to database but implement wordpress functions on custom code ? </p>\n\n<p>Just include wp-config.php file on custom code and you can use all wordpress functions.</p>\n\n<pre><code><?php\n\nrequire_once('wp-config.php');\n\n$posts = new WP_Query(...);\n</code></pre>\n\n<p>after that you can use wordpress <a href=\"https://codex.wordpress.org/Class_Reference/wpdb\" rel=\"nofollow noreferrer\">wpdb</a> class</p>\n\n<pre><code>$myrows = $wpdb->get_results( \"SELECT id, name FROM mytable\" );\n</code></pre>\n"
},
{
"answer_id": 289598,
"author": "Waleed Asender",
"author_id": 44821,
"author_profile": "https://wordpress.stackexchange.com/users/44821",
"pm_score": 0,
"selected": false,
"text": "<p>No need to do custom mysql connection, you can include wp-blog-header.php file and get all wp functionality working in your PHP file:</p>\n\n<pre><code><?php require 'PATH-TO-WP/wp-blog-header.php'; ?>\n</code></pre>\n"
},
{
"answer_id": 289608,
"author": "Clinton",
"author_id": 122375,
"author_profile": "https://wordpress.stackexchange.com/users/122375",
"pm_score": 1,
"selected": false,
"text": "<p>While it may possible to connect using mysqli->connect it is always better to make use of built in Wordpress functionality (even for external code).</p>\n\n<p>By this I mean that you should use the wpdb class. See <a href=\"https://codex.wordpress.org/Class_Reference/wpdb\" rel=\"nofollow noreferrer\">https://codex.wordpress.org/Class_Reference/wpdb</a> for more information.</p>\n\n<p>First you need to link to the Wordpress class:</p>\n\n<pre><code>echo '<h1>WP Connect DB</h1>';\necho '<p>Directory Check: '.$_SERVER['DOCUMENT_ROOT'] . '/wp-load.php</p>';\nrequire_once( $_SERVER['DOCUMENT_ROOT'] . '/wp-load.php' );\n</code></pre>\n\n<p>If you get an error, check that the path to wp-load is correct and adjust if necessary.</p>\n\n<p>Next you can define the user and database etc.</p>\n\n<pre><code>/** The name of the database for WordPress */\ndefine('DB_NAME', 'mydatabase');\n/** MySQL database username */\ndefine('DB_USER', 'myusername');\n/** MySQL database password */\ndefine('DB_PASSWORD', 'mypassword');\n/** MySQL hostname */\ndefine('DB_HOST', 'localhost');\n</code></pre>\n\n<p>This info comes straight from the wp-config.php file. These do not need to be defined as constants, you can submit these directly into the right place in the database connection code below:</p>\n\n<pre><code>$wpdb = new wpdb( DB_USER, DB_PASSWORD, DB_NAME, DB_HOST);\n</code></pre>\n\n<p>Finally you can do something with the results for example:</p>\n\n<pre><code>$rows = $wpdb->get_results( \"SELECT * FROM wp_posts\" );\necho '<h3>Results</h3><pre>'.var_export($rows,true).'</pre>';\n</code></pre>\n\n<p>Putting it all together your code would look like this:</p>\n\n<pre><code>echo '<h1>WP Connect DB</h1>';\necho '<p>Directory: '.$_SERVER['DOCUMENT_ROOT'] . '/wpdev/wp-load.php</p>';\nrequire_once( $_SERVER['DOCUMENT_ROOT'] . '/wpdev/wp-load.php' );\ndefine('SHORTINIT', true );\n/** The name of the database for WordPress */\ndefine('DB_NAME', 'mydatabase');\n/** MySQL database username */\ndefine('DB_USER', 'myusername');\n/** MySQL database password */\ndefine('DB_PASSWORD', 'mypassword');\n/** MySQL hostname */\ndefine('DB_HOST', 'localhost');\n$wpdb = new wpdb( DB_USER, DB_PASSWORD, DB_NAME, DB_HOST);\n$rows = $wpdb->get_results( \"SELECT * FROM wp_posts\" );\necho '<h3>Results</h3><pre>'.var_export($rows,true).'</pre>';\n</code></pre>\n\n<p>The additional SHORTINIT definition is added to minimise the Wordpress load but is not required.</p>\n\n<p>I hope that this helps.</p>\n"
}
]
| 2017/12/27 | [
"https://wordpress.stackexchange.com/questions/289605",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/131001/"
]
| In my Ubuntu VPS, to search and replace in a DB of a site I do for example:
```
cd /var/www/html/example.com
sudo wp search-replace "http://" "https://" --all-tables
```
Yet in Windows 10 I use XAMPP and can't do this action with WSL + WP-CLI because one cannot use Bash inside windows (yet).
My problem
----------
I have installed a backup version of an online website in Windows XAMPP and all main menu links turn to the online site so I need to change in DB from `https://` to `localhost://`.
My question
-----------
How could I easily and efficiently change the DB from `https://` to `localhost://`. in XAMPP in Windows? | While it may possible to connect using mysqli->connect it is always better to make use of built in Wordpress functionality (even for external code).
By this I mean that you should use the wpdb class. See <https://codex.wordpress.org/Class_Reference/wpdb> for more information.
First you need to link to the Wordpress class:
```
echo '<h1>WP Connect DB</h1>';
echo '<p>Directory Check: '.$_SERVER['DOCUMENT_ROOT'] . '/wp-load.php</p>';
require_once( $_SERVER['DOCUMENT_ROOT'] . '/wp-load.php' );
```
If you get an error, check that the path to wp-load is correct and adjust if necessary.
Next you can define the user and database etc.
```
/** The name of the database for WordPress */
define('DB_NAME', 'mydatabase');
/** MySQL database username */
define('DB_USER', 'myusername');
/** MySQL database password */
define('DB_PASSWORD', 'mypassword');
/** MySQL hostname */
define('DB_HOST', 'localhost');
```
This info comes straight from the wp-config.php file. These do not need to be defined as constants, you can submit these directly into the right place in the database connection code below:
```
$wpdb = new wpdb( DB_USER, DB_PASSWORD, DB_NAME, DB_HOST);
```
Finally you can do something with the results for example:
```
$rows = $wpdb->get_results( "SELECT * FROM wp_posts" );
echo '<h3>Results</h3><pre>'.var_export($rows,true).'</pre>';
```
Putting it all together your code would look like this:
```
echo '<h1>WP Connect DB</h1>';
echo '<p>Directory: '.$_SERVER['DOCUMENT_ROOT'] . '/wpdev/wp-load.php</p>';
require_once( $_SERVER['DOCUMENT_ROOT'] . '/wpdev/wp-load.php' );
define('SHORTINIT', true );
/** The name of the database for WordPress */
define('DB_NAME', 'mydatabase');
/** MySQL database username */
define('DB_USER', 'myusername');
/** MySQL database password */
define('DB_PASSWORD', 'mypassword');
/** MySQL hostname */
define('DB_HOST', 'localhost');
$wpdb = new wpdb( DB_USER, DB_PASSWORD, DB_NAME, DB_HOST);
$rows = $wpdb->get_results( "SELECT * FROM wp_posts" );
echo '<h3>Results</h3><pre>'.var_export($rows,true).'</pre>';
```
The additional SHORTINIT definition is added to minimise the Wordpress load but is not required.
I hope that this helps. |
289,622 | <p>I've looked through all the similar threads I can find, and I think I <em>should</em> have all the pieces in place to have translated strings appear, but they are not. I'm about ready to pull out my hair!</p>
<p>Here's what I've got going - I'm making a custom theme (based on the _s starter), and I have added templates for some custom post types (created in my own plugins). I installed the Loco Translate plugin to create and edit po/mo files. The files are stored in 'mytheme/languages'.</p>
<p>In my theme's functions.php I have:</p>
<pre><code>/**
* Load theme text domain for translations
*/
function mytheme_load_theme_textdomain() {
if (load_theme_textdomain('mytheme', get_template_directory() . '/languages')) {
error_log("Text Domain loaded.");
}
}
add_action('after_setup_theme', 'mytheme_load_theme_textdomain');
</code></pre>
<p>In my template part file, I have the strings set up for display like this:</p>
<p><code><?php _e('My String Text', 'mytheme'); ?></code></p>
<p>When I load the page that should have the translated strings, then look at the debug.log file, I see the message "Text Domain loaded." So that part should be working. Loco Translate correctly sees the strings and allows me to translate them. So everything in the .mo file should be correct.</p>
<p>I have tried hardcoding the locale in wp-config.php (just to check) by adding <code>define('WPLANG', 'es_ES');</code> and echoing the global <code>$locale</code> variable to the debug log from within the function described above. That works correctly.</p>
<p>Edit: adding output from debug-mo-translations plugin</p>
<pre><code>Debug MO Translations (Version 1.0)
Locale: es_ES
Domain: mytheme
File: /wp-content/languages/themes/mytheme-es_ES.mo (not found)
Called in: /wp-includes/l10n.php line 792 load_textdomain
Domain: mytheme
File: /wp-content/languages/loco/themes/mytheme-es_ES.mo (not found)
Called in: /wp-content/plugins/loco-translate/src/hooks/LoadHelper.php line 103 load_textdomain
Domain: mytheme
File: /wp-content/themes/mytheme/languages/es_ES.mo (0.62kb)
Called in: /wp-includes/l10n.php line 800 load_textdomain
</code></pre>
<p>So, I've got translatable strings in my template file, I've got translations in .po/.mo files within my theme, the locale is correctly set, and I load my theme text domain in my functions.php file. But the strings still do not appear in translated form on the front end! What am I missing?</p>
<p>Thanks in advance!</p>
| [
{
"answer_id": 289594,
"author": "D. Dan",
"author_id": 133528,
"author_profile": "https://wordpress.stackexchange.com/users/133528",
"pm_score": 0,
"selected": false,
"text": "<p>Try using <a href=\"https://codex.wordpress.org/Class_Reference/wpdb\" rel=\"nofollow noreferrer\">wpdb</a>. It's the built in class for handling external databases.</p>\n"
},
{
"answer_id": 289595,
"author": "Nefro",
"author_id": 86801,
"author_profile": "https://wordpress.stackexchange.com/users/86801",
"pm_score": 0,
"selected": false,
"text": "<p>Maybe you don't need connect to database but implement wordpress functions on custom code ? </p>\n\n<p>Just include wp-config.php file on custom code and you can use all wordpress functions.</p>\n\n<pre><code><?php\n\nrequire_once('wp-config.php');\n\n$posts = new WP_Query(...);\n</code></pre>\n\n<p>after that you can use wordpress <a href=\"https://codex.wordpress.org/Class_Reference/wpdb\" rel=\"nofollow noreferrer\">wpdb</a> class</p>\n\n<pre><code>$myrows = $wpdb->get_results( \"SELECT id, name FROM mytable\" );\n</code></pre>\n"
},
{
"answer_id": 289598,
"author": "Waleed Asender",
"author_id": 44821,
"author_profile": "https://wordpress.stackexchange.com/users/44821",
"pm_score": 0,
"selected": false,
"text": "<p>No need to do custom mysql connection, you can include wp-blog-header.php file and get all wp functionality working in your PHP file:</p>\n\n<pre><code><?php require 'PATH-TO-WP/wp-blog-header.php'; ?>\n</code></pre>\n"
},
{
"answer_id": 289608,
"author": "Clinton",
"author_id": 122375,
"author_profile": "https://wordpress.stackexchange.com/users/122375",
"pm_score": 1,
"selected": false,
"text": "<p>While it may possible to connect using mysqli->connect it is always better to make use of built in Wordpress functionality (even for external code).</p>\n\n<p>By this I mean that you should use the wpdb class. See <a href=\"https://codex.wordpress.org/Class_Reference/wpdb\" rel=\"nofollow noreferrer\">https://codex.wordpress.org/Class_Reference/wpdb</a> for more information.</p>\n\n<p>First you need to link to the Wordpress class:</p>\n\n<pre><code>echo '<h1>WP Connect DB</h1>';\necho '<p>Directory Check: '.$_SERVER['DOCUMENT_ROOT'] . '/wp-load.php</p>';\nrequire_once( $_SERVER['DOCUMENT_ROOT'] . '/wp-load.php' );\n</code></pre>\n\n<p>If you get an error, check that the path to wp-load is correct and adjust if necessary.</p>\n\n<p>Next you can define the user and database etc.</p>\n\n<pre><code>/** The name of the database for WordPress */\ndefine('DB_NAME', 'mydatabase');\n/** MySQL database username */\ndefine('DB_USER', 'myusername');\n/** MySQL database password */\ndefine('DB_PASSWORD', 'mypassword');\n/** MySQL hostname */\ndefine('DB_HOST', 'localhost');\n</code></pre>\n\n<p>This info comes straight from the wp-config.php file. These do not need to be defined as constants, you can submit these directly into the right place in the database connection code below:</p>\n\n<pre><code>$wpdb = new wpdb( DB_USER, DB_PASSWORD, DB_NAME, DB_HOST);\n</code></pre>\n\n<p>Finally you can do something with the results for example:</p>\n\n<pre><code>$rows = $wpdb->get_results( \"SELECT * FROM wp_posts\" );\necho '<h3>Results</h3><pre>'.var_export($rows,true).'</pre>';\n</code></pre>\n\n<p>Putting it all together your code would look like this:</p>\n\n<pre><code>echo '<h1>WP Connect DB</h1>';\necho '<p>Directory: '.$_SERVER['DOCUMENT_ROOT'] . '/wpdev/wp-load.php</p>';\nrequire_once( $_SERVER['DOCUMENT_ROOT'] . '/wpdev/wp-load.php' );\ndefine('SHORTINIT', true );\n/** The name of the database for WordPress */\ndefine('DB_NAME', 'mydatabase');\n/** MySQL database username */\ndefine('DB_USER', 'myusername');\n/** MySQL database password */\ndefine('DB_PASSWORD', 'mypassword');\n/** MySQL hostname */\ndefine('DB_HOST', 'localhost');\n$wpdb = new wpdb( DB_USER, DB_PASSWORD, DB_NAME, DB_HOST);\n$rows = $wpdb->get_results( \"SELECT * FROM wp_posts\" );\necho '<h3>Results</h3><pre>'.var_export($rows,true).'</pre>';\n</code></pre>\n\n<p>The additional SHORTINIT definition is added to minimise the Wordpress load but is not required.</p>\n\n<p>I hope that this helps.</p>\n"
}
]
| 2017/12/27 | [
"https://wordpress.stackexchange.com/questions/289622",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/69989/"
]
| I've looked through all the similar threads I can find, and I think I *should* have all the pieces in place to have translated strings appear, but they are not. I'm about ready to pull out my hair!
Here's what I've got going - I'm making a custom theme (based on the \_s starter), and I have added templates for some custom post types (created in my own plugins). I installed the Loco Translate plugin to create and edit po/mo files. The files are stored in 'mytheme/languages'.
In my theme's functions.php I have:
```
/**
* Load theme text domain for translations
*/
function mytheme_load_theme_textdomain() {
if (load_theme_textdomain('mytheme', get_template_directory() . '/languages')) {
error_log("Text Domain loaded.");
}
}
add_action('after_setup_theme', 'mytheme_load_theme_textdomain');
```
In my template part file, I have the strings set up for display like this:
`<?php _e('My String Text', 'mytheme'); ?>`
When I load the page that should have the translated strings, then look at the debug.log file, I see the message "Text Domain loaded." So that part should be working. Loco Translate correctly sees the strings and allows me to translate them. So everything in the .mo file should be correct.
I have tried hardcoding the locale in wp-config.php (just to check) by adding `define('WPLANG', 'es_ES');` and echoing the global `$locale` variable to the debug log from within the function described above. That works correctly.
Edit: adding output from debug-mo-translations plugin
```
Debug MO Translations (Version 1.0)
Locale: es_ES
Domain: mytheme
File: /wp-content/languages/themes/mytheme-es_ES.mo (not found)
Called in: /wp-includes/l10n.php line 792 load_textdomain
Domain: mytheme
File: /wp-content/languages/loco/themes/mytheme-es_ES.mo (not found)
Called in: /wp-content/plugins/loco-translate/src/hooks/LoadHelper.php line 103 load_textdomain
Domain: mytheme
File: /wp-content/themes/mytheme/languages/es_ES.mo (0.62kb)
Called in: /wp-includes/l10n.php line 800 load_textdomain
```
So, I've got translatable strings in my template file, I've got translations in .po/.mo files within my theme, the locale is correctly set, and I load my theme text domain in my functions.php file. But the strings still do not appear in translated form on the front end! What am I missing?
Thanks in advance! | While it may possible to connect using mysqli->connect it is always better to make use of built in Wordpress functionality (even for external code).
By this I mean that you should use the wpdb class. See <https://codex.wordpress.org/Class_Reference/wpdb> for more information.
First you need to link to the Wordpress class:
```
echo '<h1>WP Connect DB</h1>';
echo '<p>Directory Check: '.$_SERVER['DOCUMENT_ROOT'] . '/wp-load.php</p>';
require_once( $_SERVER['DOCUMENT_ROOT'] . '/wp-load.php' );
```
If you get an error, check that the path to wp-load is correct and adjust if necessary.
Next you can define the user and database etc.
```
/** The name of the database for WordPress */
define('DB_NAME', 'mydatabase');
/** MySQL database username */
define('DB_USER', 'myusername');
/** MySQL database password */
define('DB_PASSWORD', 'mypassword');
/** MySQL hostname */
define('DB_HOST', 'localhost');
```
This info comes straight from the wp-config.php file. These do not need to be defined as constants, you can submit these directly into the right place in the database connection code below:
```
$wpdb = new wpdb( DB_USER, DB_PASSWORD, DB_NAME, DB_HOST);
```
Finally you can do something with the results for example:
```
$rows = $wpdb->get_results( "SELECT * FROM wp_posts" );
echo '<h3>Results</h3><pre>'.var_export($rows,true).'</pre>';
```
Putting it all together your code would look like this:
```
echo '<h1>WP Connect DB</h1>';
echo '<p>Directory: '.$_SERVER['DOCUMENT_ROOT'] . '/wpdev/wp-load.php</p>';
require_once( $_SERVER['DOCUMENT_ROOT'] . '/wpdev/wp-load.php' );
define('SHORTINIT', true );
/** The name of the database for WordPress */
define('DB_NAME', 'mydatabase');
/** MySQL database username */
define('DB_USER', 'myusername');
/** MySQL database password */
define('DB_PASSWORD', 'mypassword');
/** MySQL hostname */
define('DB_HOST', 'localhost');
$wpdb = new wpdb( DB_USER, DB_PASSWORD, DB_NAME, DB_HOST);
$rows = $wpdb->get_results( "SELECT * FROM wp_posts" );
echo '<h3>Results</h3><pre>'.var_export($rows,true).'</pre>';
```
The additional SHORTINIT definition is added to minimise the Wordpress load but is not required.
I hope that this helps. |
289,623 | <p>I need to remove some external .js files from source
here is source: view-source:buhehe.de/ausmalbilder/
There is 3 jquery library and I don't know what is difference, why is it not one enough?</p>
<pre><code><script type='text/javascript' src='http://buhehe.de/wp-includes/js/jquery/jquery.js?ver=1.12.4'></script>
<script type='text/javascript' src='http://buhehe.de/wp-includes/js/jquery/jquery-migrate.min.js?ver=1.4.1'></script>
<script type="text/javascript" src="http://buhehe.de/wp-content/themes/tema/js/jquery-3.2.1.min.js"></script>
</code></pre>
<p>Can I leave only one?</p>
<p>And how can I remove following:</p>
<pre><code><script type='text/javascript' src='http://buhehe.de/wp-content/themes/heatt/js/small-menu.js?ver=4.9.1'></script>
<script type='text/javascript' src='http://buhehe.de/wp-includes/js/wp-embed.min.js?ver=4.9.1'></script>
</code></pre>
| [
{
"answer_id": 289624,
"author": "Nicolai Grossherr",
"author_id": 22534,
"author_profile": "https://wordpress.stackexchange.com/users/22534",
"pm_score": 2,
"selected": false,
"text": "<p>Firstly: Are you absolutely sure that you don't need them?</p>\n\n<p>Secondly: I'm assuming <code>small-menu.js</code> is for the mobile menu and <code>wp-embed.min.js</code> you want in case you use embeds.<br>\nIf I'm right, then you might want to keep the former. Aside from that you likely will find a <code>wp_enqueue_script</code> line for the former in your theme's <code>functions.php</code>. For the latter take a look at Β»<a href=\"https://wordpress.stackexchange.com/q/211701/22534\">What does wp-embed.min.js do in WordPress 4.4?</a>Β«.<br>\nTo keep it short and simple about the jQuery lines, WordPress loads <code>jquery.js</code> and <code>jquery-migrate.min.js</code> for compatibility reasons. I would suggest you keep it that way, unless you are really sure what you're doing.<br>\nAdditionally your theme loads another jQuery source, which generally isn't recommended. But there might be a reason to do so, so it can't be easily answered, if you simply can remove it. You'll likely find this one it the <code>functions.php</code> as a <code>wp_enqueue_script</code> line too.</p>\n"
},
{
"answer_id": 289629,
"author": "Liam Stewart",
"author_id": 121955,
"author_profile": "https://wordpress.stackexchange.com/users/121955",
"pm_score": 2,
"selected": false,
"text": "<p>You can use wp_dequeue_script to achieve this assuming they are using wp_enqueue_script to add the scripts in the first place.</p>\n\n<p>Learn more about enquene and dequeue:\n<a href=\"https://developer.wordpress.org/reference/functions/wp_enqueue_script/\" rel=\"nofollow noreferrer\">https://developer.wordpress.org/reference/functions/wp_enqueue_script/</a>\n<a href=\"https://codex.wordpress.org/Function_Reference/wp_dequeue_script\" rel=\"nofollow noreferrer\">https://codex.wordpress.org/Function_Reference/wp_dequeue_script</a></p>\n\n<pre><code>function dequeue_script() {\n wp_dequeue_script( 'http://buhehe.de/wp-content/themes/heatt/js/small-menu.js?ver=4.9.1' );\n wp_dequeue_script( 'http://buhehe.de/wp-includes/js/wp-embed.min.js?ver=4.9.1' );\n}\nadd_action( 'wp_print_scripts', 'dequeue_script', 100 );\n</code></pre>\n"
}
]
| 2017/12/27 | [
"https://wordpress.stackexchange.com/questions/289623",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/133900/"
]
| I need to remove some external .js files from source
here is source: view-source:buhehe.de/ausmalbilder/
There is 3 jquery library and I don't know what is difference, why is it not one enough?
```
<script type='text/javascript' src='http://buhehe.de/wp-includes/js/jquery/jquery.js?ver=1.12.4'></script>
<script type='text/javascript' src='http://buhehe.de/wp-includes/js/jquery/jquery-migrate.min.js?ver=1.4.1'></script>
<script type="text/javascript" src="http://buhehe.de/wp-content/themes/tema/js/jquery-3.2.1.min.js"></script>
```
Can I leave only one?
And how can I remove following:
```
<script type='text/javascript' src='http://buhehe.de/wp-content/themes/heatt/js/small-menu.js?ver=4.9.1'></script>
<script type='text/javascript' src='http://buhehe.de/wp-includes/js/wp-embed.min.js?ver=4.9.1'></script>
``` | Firstly: Are you absolutely sure that you don't need them?
Secondly: I'm assuming `small-menu.js` is for the mobile menu and `wp-embed.min.js` you want in case you use embeds.
If I'm right, then you might want to keep the former. Aside from that you likely will find a `wp_enqueue_script` line for the former in your theme's `functions.php`. For the latter take a look at Β»[What does wp-embed.min.js do in WordPress 4.4?](https://wordpress.stackexchange.com/q/211701/22534)Β«.
To keep it short and simple about the jQuery lines, WordPress loads `jquery.js` and `jquery-migrate.min.js` for compatibility reasons. I would suggest you keep it that way, unless you are really sure what you're doing.
Additionally your theme loads another jQuery source, which generally isn't recommended. But there might be a reason to do so, so it can't be easily answered, if you simply can remove it. You'll likely find this one it the `functions.php` as a `wp_enqueue_script` line too. |
289,634 | <p>This is my code:</p>
<pre><code>$args = array (
'order' => 'DESC',
'include' => get_user_meta($author->ID, 'the_following_users', true)
);
$wp_user_query = new WP_User_Query( $args );
$users = $wp_user_query->get_results();
if ( ! empty( $users ) ) {
foreach ( $users as $user ) {
// Get users
}
} else {
echo 'Error.';
}
</code></pre>
<p>The user meta 'the_users' may be empty so if it's empty it's got to me all registered users if not empty it's print the users that I need.</p>
<p>The problem that <code>if ( ! empty( $users ) ) { }</code> is not reading if 'include' is empty or not, I know I can make a variable and check first if the variable is empty or not but I don't need this I want to check if 'include' is empty by using '$wp_user_query->get_results()'.</p>
<p><strong>EDIT:</strong></p>
<p>As Nicolai answer we can replace true to false from get_user_meta code and the problem will be solved and if the include is empty the WP-User_Query will return a false and print error.</p>
<p>The problem now that if include not empty so the code must be working without any issues but that does not happen it ignores the users that stored in 'the_users' user meta and print only current user.</p>
<p>Here's the value of 'the_users' user meta:</p>
<pre><code>a:19:{i:0;s:2:"89";i:3;s:3:"105";i:4;s:2:"74";i:5;s:3:"111";i:6;s:3:"167";i:7;s:2:"83";i:8;s:2:"54";i:9;s:2:"87";i:10;s:2:"85";i:11;s:2:"77";i:13;s:2:"82";i:14;s:2:"60";i:15;s:3:"149";i:16;s:3:"160";i:17;s:2:"71";i:18;s:1:"3";i:19;s:1:"2";i:20;s:3:"121";i:21;s:2:"57";}
</code></pre>
<p>Here's how i stored 'the_users' user meta data:</p>
<pre><code>$the_following_users = get_user_meta($the_follower, "the_following_users", true);
if(!in_array($user_follow_to, $the_following_users) && is_array($the_following_users)){
$the_following_users[] = $user_follow_to;
} else {
$the_following_users = array($user_follow_to);
}
update_user_meta($the_follower, "the_following_users", $the_following_users);
</code></pre>
| [
{
"answer_id": 289636,
"author": "Nicolai Grossherr",
"author_id": 22534,
"author_profile": "https://wordpress.stackexchange.com/users/22534",
"pm_score": 2,
"selected": false,
"text": "<p>The <code>include</code> parameter of <code>WP_User_Query</code> expects an array as argument. So set the <code>$single</code> parameter of <code>get_user_meta</code> to <code>false</code>. Or don't use it, because <code>false</code> is the default. </p>\n\n<pre><code>// USE\nget_user_meta( $author->ID, 'the_users', false )\n// OR\nget_user_meta( $author->ID, 'the_users' )\n</code></pre>\n"
},
{
"answer_id": 289665,
"author": "Tom J Nowell",
"author_id": 736,
"author_profile": "https://wordpress.stackexchange.com/users/736",
"pm_score": 2,
"selected": true,
"text": "<p>I think the problem here is that in the process of violating this rule, you've created confusion and problems:</p>\n<blockquote>\n<p>do 1 thing per statement, 1 statement per line</p>\n</blockquote>\n<p>Coupled with another problem:</p>\n<blockquote>\n<p>Passing arrays to the APIs which get stored as serialised PHP ( security issue )</p>\n</blockquote>\n<p>And another:</p>\n<blockquote>\n<p>Always check your assumptions</p>\n<p>it ignores the users that stored in 'the_users' user meta and print only current user.</p>\n</blockquote>\n<p>That last one is the killer here. You never check for error values on <code>get_user_meta</code>, leading to errors. Users don't start out with <code>the_users</code> meta, it has to be added.</p>\n<p>Run through this code in your mind, e.g.:</p>\n<pre><code>$the_following_users = ''; //get_user_meta($the_follower, "the_following_users", true);\n\nif(!in_array($user_follow_to, $the_following_users) && is_array($the_following_users)){\n $the_following_users[] = $user_follow_to;\n</code></pre>\n<p>Here there is no check on <code>$the_following_users</code>, which may not be an array at all, but a <code>false</code> or an empty string.</p>\n<p>So lets fix the saving:</p>\n<pre><code>$the_following_users = get_user_meta($the_follower, "the_following_users", true);\nif ( empty( $the_following_users ) ) {\n $the_following_user = array();\n}\n</code></pre>\n<p>Then lets simplify the next part:</p>\n<pre><code>$the_following_users[] = $user_follow_to;\n</code></pre>\n<p>And fix the saving so that it's not a security risk:</p>\n<pre><code>$following = implode( ',', $the_following_users );\nupdate_user_meta($the_follower, "the_following_users", $following );\n</code></pre>\n<p>Finally, lets move to the frontend:</p>\n<p>Firstly, we assume the <code>get_user_meta</code> works, but never check if this is true:</p>\n<pre><code>$args = array (\n 'order' => 'DESC',\n 'include' => get_user_meta($author->ID, 'the_following_users', true)\n);\n</code></pre>\n<p>What if the user has never followed anybody before? What if they unfollowed everyone? That would break everything! So lets fix that and switch it over to the comma separated list format:</p>\n<pre><code>$include = get_user_meta($author->ID, 'the_following_users', true);\nif ( empty( $include ) ) {\n // the user follows nobody, or has not followed anybody yet!\n} else {\n // turn the string into an array\n $include = explode( ',', $include );\n $args = array (\n 'order' => 'DESC',\n 'include' => $include\n );\n // etc...\n}\n</code></pre>\n<h1>A Final Note</h1>\n<p>Your loop looks like this:</p>\n<pre><code>foreach ( $users as $user ) {\n // Get users\n}\n</code></pre>\n<p>But you never share the code inside the loop, which could be why you're having issues. For example, <code>the_author</code> always refers to the author of the current post. If you want to display information about the <code>$user</code>, you would need to pass its ID, or user the public properties, e.g.</p>\n<pre><code>foreach ( $users as $user ) {\n // Get users\n echo esc_html( $user->first_name . ' ' . $user->last_name );\n}\n</code></pre>\n"
}
]
| 2017/12/27 | [
"https://wordpress.stackexchange.com/questions/289634",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/133343/"
]
| This is my code:
```
$args = array (
'order' => 'DESC',
'include' => get_user_meta($author->ID, 'the_following_users', true)
);
$wp_user_query = new WP_User_Query( $args );
$users = $wp_user_query->get_results();
if ( ! empty( $users ) ) {
foreach ( $users as $user ) {
// Get users
}
} else {
echo 'Error.';
}
```
The user meta 'the\_users' may be empty so if it's empty it's got to me all registered users if not empty it's print the users that I need.
The problem that `if ( ! empty( $users ) ) { }` is not reading if 'include' is empty or not, I know I can make a variable and check first if the variable is empty or not but I don't need this I want to check if 'include' is empty by using '$wp\_user\_query->get\_results()'.
**EDIT:**
As Nicolai answer we can replace true to false from get\_user\_meta code and the problem will be solved and if the include is empty the WP-User\_Query will return a false and print error.
The problem now that if include not empty so the code must be working without any issues but that does not happen it ignores the users that stored in 'the\_users' user meta and print only current user.
Here's the value of 'the\_users' user meta:
```
a:19:{i:0;s:2:"89";i:3;s:3:"105";i:4;s:2:"74";i:5;s:3:"111";i:6;s:3:"167";i:7;s:2:"83";i:8;s:2:"54";i:9;s:2:"87";i:10;s:2:"85";i:11;s:2:"77";i:13;s:2:"82";i:14;s:2:"60";i:15;s:3:"149";i:16;s:3:"160";i:17;s:2:"71";i:18;s:1:"3";i:19;s:1:"2";i:20;s:3:"121";i:21;s:2:"57";}
```
Here's how i stored 'the\_users' user meta data:
```
$the_following_users = get_user_meta($the_follower, "the_following_users", true);
if(!in_array($user_follow_to, $the_following_users) && is_array($the_following_users)){
$the_following_users[] = $user_follow_to;
} else {
$the_following_users = array($user_follow_to);
}
update_user_meta($the_follower, "the_following_users", $the_following_users);
``` | I think the problem here is that in the process of violating this rule, you've created confusion and problems:
>
> do 1 thing per statement, 1 statement per line
>
>
>
Coupled with another problem:
>
> Passing arrays to the APIs which get stored as serialised PHP ( security issue )
>
>
>
And another:
>
> Always check your assumptions
>
>
> it ignores the users that stored in 'the\_users' user meta and print only current user.
>
>
>
That last one is the killer here. You never check for error values on `get_user_meta`, leading to errors. Users don't start out with `the_users` meta, it has to be added.
Run through this code in your mind, e.g.:
```
$the_following_users = ''; //get_user_meta($the_follower, "the_following_users", true);
if(!in_array($user_follow_to, $the_following_users) && is_array($the_following_users)){
$the_following_users[] = $user_follow_to;
```
Here there is no check on `$the_following_users`, which may not be an array at all, but a `false` or an empty string.
So lets fix the saving:
```
$the_following_users = get_user_meta($the_follower, "the_following_users", true);
if ( empty( $the_following_users ) ) {
$the_following_user = array();
}
```
Then lets simplify the next part:
```
$the_following_users[] = $user_follow_to;
```
And fix the saving so that it's not a security risk:
```
$following = implode( ',', $the_following_users );
update_user_meta($the_follower, "the_following_users", $following );
```
Finally, lets move to the frontend:
Firstly, we assume the `get_user_meta` works, but never check if this is true:
```
$args = array (
'order' => 'DESC',
'include' => get_user_meta($author->ID, 'the_following_users', true)
);
```
What if the user has never followed anybody before? What if they unfollowed everyone? That would break everything! So lets fix that and switch it over to the comma separated list format:
```
$include = get_user_meta($author->ID, 'the_following_users', true);
if ( empty( $include ) ) {
// the user follows nobody, or has not followed anybody yet!
} else {
// turn the string into an array
$include = explode( ',', $include );
$args = array (
'order' => 'DESC',
'include' => $include
);
// etc...
}
```
A Final Note
============
Your loop looks like this:
```
foreach ( $users as $user ) {
// Get users
}
```
But you never share the code inside the loop, which could be why you're having issues. For example, `the_author` always refers to the author of the current post. If you want to display information about the `$user`, you would need to pass its ID, or user the public properties, e.g.
```
foreach ( $users as $user ) {
// Get users
echo esc_html( $user->first_name . ' ' . $user->last_name );
}
``` |
289,640 | <p>I'm using Tevolution. I can't find where I can re-size the flag at the top of this website: <a href="http://www.isupportblack.com/" rel="nofollow noreferrer">isupportblack.com</a> It is blurry and shouldn't be. Any suggestions? Thanks!</p>
| [
{
"answer_id": 289636,
"author": "Nicolai Grossherr",
"author_id": 22534,
"author_profile": "https://wordpress.stackexchange.com/users/22534",
"pm_score": 2,
"selected": false,
"text": "<p>The <code>include</code> parameter of <code>WP_User_Query</code> expects an array as argument. So set the <code>$single</code> parameter of <code>get_user_meta</code> to <code>false</code>. Or don't use it, because <code>false</code> is the default. </p>\n\n<pre><code>// USE\nget_user_meta( $author->ID, 'the_users', false )\n// OR\nget_user_meta( $author->ID, 'the_users' )\n</code></pre>\n"
},
{
"answer_id": 289665,
"author": "Tom J Nowell",
"author_id": 736,
"author_profile": "https://wordpress.stackexchange.com/users/736",
"pm_score": 2,
"selected": true,
"text": "<p>I think the problem here is that in the process of violating this rule, you've created confusion and problems:</p>\n<blockquote>\n<p>do 1 thing per statement, 1 statement per line</p>\n</blockquote>\n<p>Coupled with another problem:</p>\n<blockquote>\n<p>Passing arrays to the APIs which get stored as serialised PHP ( security issue )</p>\n</blockquote>\n<p>And another:</p>\n<blockquote>\n<p>Always check your assumptions</p>\n<p>it ignores the users that stored in 'the_users' user meta and print only current user.</p>\n</blockquote>\n<p>That last one is the killer here. You never check for error values on <code>get_user_meta</code>, leading to errors. Users don't start out with <code>the_users</code> meta, it has to be added.</p>\n<p>Run through this code in your mind, e.g.:</p>\n<pre><code>$the_following_users = ''; //get_user_meta($the_follower, "the_following_users", true);\n\nif(!in_array($user_follow_to, $the_following_users) && is_array($the_following_users)){\n $the_following_users[] = $user_follow_to;\n</code></pre>\n<p>Here there is no check on <code>$the_following_users</code>, which may not be an array at all, but a <code>false</code> or an empty string.</p>\n<p>So lets fix the saving:</p>\n<pre><code>$the_following_users = get_user_meta($the_follower, "the_following_users", true);\nif ( empty( $the_following_users ) ) {\n $the_following_user = array();\n}\n</code></pre>\n<p>Then lets simplify the next part:</p>\n<pre><code>$the_following_users[] = $user_follow_to;\n</code></pre>\n<p>And fix the saving so that it's not a security risk:</p>\n<pre><code>$following = implode( ',', $the_following_users );\nupdate_user_meta($the_follower, "the_following_users", $following );\n</code></pre>\n<p>Finally, lets move to the frontend:</p>\n<p>Firstly, we assume the <code>get_user_meta</code> works, but never check if this is true:</p>\n<pre><code>$args = array (\n 'order' => 'DESC',\n 'include' => get_user_meta($author->ID, 'the_following_users', true)\n);\n</code></pre>\n<p>What if the user has never followed anybody before? What if they unfollowed everyone? That would break everything! So lets fix that and switch it over to the comma separated list format:</p>\n<pre><code>$include = get_user_meta($author->ID, 'the_following_users', true);\nif ( empty( $include ) ) {\n // the user follows nobody, or has not followed anybody yet!\n} else {\n // turn the string into an array\n $include = explode( ',', $include );\n $args = array (\n 'order' => 'DESC',\n 'include' => $include\n );\n // etc...\n}\n</code></pre>\n<h1>A Final Note</h1>\n<p>Your loop looks like this:</p>\n<pre><code>foreach ( $users as $user ) {\n // Get users\n}\n</code></pre>\n<p>But you never share the code inside the loop, which could be why you're having issues. For example, <code>the_author</code> always refers to the author of the current post. If you want to display information about the <code>$user</code>, you would need to pass its ID, or user the public properties, e.g.</p>\n<pre><code>foreach ( $users as $user ) {\n // Get users\n echo esc_html( $user->first_name . ' ' . $user->last_name );\n}\n</code></pre>\n"
}
]
| 2017/12/28 | [
"https://wordpress.stackexchange.com/questions/289640",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/133907/"
]
| I'm using Tevolution. I can't find where I can re-size the flag at the top of this website: [isupportblack.com](http://www.isupportblack.com/) It is blurry and shouldn't be. Any suggestions? Thanks! | I think the problem here is that in the process of violating this rule, you've created confusion and problems:
>
> do 1 thing per statement, 1 statement per line
>
>
>
Coupled with another problem:
>
> Passing arrays to the APIs which get stored as serialised PHP ( security issue )
>
>
>
And another:
>
> Always check your assumptions
>
>
> it ignores the users that stored in 'the\_users' user meta and print only current user.
>
>
>
That last one is the killer here. You never check for error values on `get_user_meta`, leading to errors. Users don't start out with `the_users` meta, it has to be added.
Run through this code in your mind, e.g.:
```
$the_following_users = ''; //get_user_meta($the_follower, "the_following_users", true);
if(!in_array($user_follow_to, $the_following_users) && is_array($the_following_users)){
$the_following_users[] = $user_follow_to;
```
Here there is no check on `$the_following_users`, which may not be an array at all, but a `false` or an empty string.
So lets fix the saving:
```
$the_following_users = get_user_meta($the_follower, "the_following_users", true);
if ( empty( $the_following_users ) ) {
$the_following_user = array();
}
```
Then lets simplify the next part:
```
$the_following_users[] = $user_follow_to;
```
And fix the saving so that it's not a security risk:
```
$following = implode( ',', $the_following_users );
update_user_meta($the_follower, "the_following_users", $following );
```
Finally, lets move to the frontend:
Firstly, we assume the `get_user_meta` works, but never check if this is true:
```
$args = array (
'order' => 'DESC',
'include' => get_user_meta($author->ID, 'the_following_users', true)
);
```
What if the user has never followed anybody before? What if they unfollowed everyone? That would break everything! So lets fix that and switch it over to the comma separated list format:
```
$include = get_user_meta($author->ID, 'the_following_users', true);
if ( empty( $include ) ) {
// the user follows nobody, or has not followed anybody yet!
} else {
// turn the string into an array
$include = explode( ',', $include );
$args = array (
'order' => 'DESC',
'include' => $include
);
// etc...
}
```
A Final Note
============
Your loop looks like this:
```
foreach ( $users as $user ) {
// Get users
}
```
But you never share the code inside the loop, which could be why you're having issues. For example, `the_author` always refers to the author of the current post. If you want to display information about the `$user`, you would need to pass its ID, or user the public properties, e.g.
```
foreach ( $users as $user ) {
// Get users
echo esc_html( $user->first_name . ' ' . $user->last_name );
}
``` |
289,666 | <p>When I try to upload any PNG file, I get the following error message:</p>
<p><a href="https://i.stack.imgur.com/JYE8w.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/JYE8w.png" alt="enter image description here"></a></p>
<p>I have no plugin or anything installed, that could cause this. I even added the following line in order to fix this:</p>
<p><code>define('ALLOW_UNFILTERED_UPLOADS', true);</code></p>
<p>Since it is a local installation, security is not an issue. But still this didn't fix my problem. Any ideas what could cause this problem?</p>
| [
{
"answer_id": 289636,
"author": "Nicolai Grossherr",
"author_id": 22534,
"author_profile": "https://wordpress.stackexchange.com/users/22534",
"pm_score": 2,
"selected": false,
"text": "<p>The <code>include</code> parameter of <code>WP_User_Query</code> expects an array as argument. So set the <code>$single</code> parameter of <code>get_user_meta</code> to <code>false</code>. Or don't use it, because <code>false</code> is the default. </p>\n\n<pre><code>// USE\nget_user_meta( $author->ID, 'the_users', false )\n// OR\nget_user_meta( $author->ID, 'the_users' )\n</code></pre>\n"
},
{
"answer_id": 289665,
"author": "Tom J Nowell",
"author_id": 736,
"author_profile": "https://wordpress.stackexchange.com/users/736",
"pm_score": 2,
"selected": true,
"text": "<p>I think the problem here is that in the process of violating this rule, you've created confusion and problems:</p>\n<blockquote>\n<p>do 1 thing per statement, 1 statement per line</p>\n</blockquote>\n<p>Coupled with another problem:</p>\n<blockquote>\n<p>Passing arrays to the APIs which get stored as serialised PHP ( security issue )</p>\n</blockquote>\n<p>And another:</p>\n<blockquote>\n<p>Always check your assumptions</p>\n<p>it ignores the users that stored in 'the_users' user meta and print only current user.</p>\n</blockquote>\n<p>That last one is the killer here. You never check for error values on <code>get_user_meta</code>, leading to errors. Users don't start out with <code>the_users</code> meta, it has to be added.</p>\n<p>Run through this code in your mind, e.g.:</p>\n<pre><code>$the_following_users = ''; //get_user_meta($the_follower, "the_following_users", true);\n\nif(!in_array($user_follow_to, $the_following_users) && is_array($the_following_users)){\n $the_following_users[] = $user_follow_to;\n</code></pre>\n<p>Here there is no check on <code>$the_following_users</code>, which may not be an array at all, but a <code>false</code> or an empty string.</p>\n<p>So lets fix the saving:</p>\n<pre><code>$the_following_users = get_user_meta($the_follower, "the_following_users", true);\nif ( empty( $the_following_users ) ) {\n $the_following_user = array();\n}\n</code></pre>\n<p>Then lets simplify the next part:</p>\n<pre><code>$the_following_users[] = $user_follow_to;\n</code></pre>\n<p>And fix the saving so that it's not a security risk:</p>\n<pre><code>$following = implode( ',', $the_following_users );\nupdate_user_meta($the_follower, "the_following_users", $following );\n</code></pre>\n<p>Finally, lets move to the frontend:</p>\n<p>Firstly, we assume the <code>get_user_meta</code> works, but never check if this is true:</p>\n<pre><code>$args = array (\n 'order' => 'DESC',\n 'include' => get_user_meta($author->ID, 'the_following_users', true)\n);\n</code></pre>\n<p>What if the user has never followed anybody before? What if they unfollowed everyone? That would break everything! So lets fix that and switch it over to the comma separated list format:</p>\n<pre><code>$include = get_user_meta($author->ID, 'the_following_users', true);\nif ( empty( $include ) ) {\n // the user follows nobody, or has not followed anybody yet!\n} else {\n // turn the string into an array\n $include = explode( ',', $include );\n $args = array (\n 'order' => 'DESC',\n 'include' => $include\n );\n // etc...\n}\n</code></pre>\n<h1>A Final Note</h1>\n<p>Your loop looks like this:</p>\n<pre><code>foreach ( $users as $user ) {\n // Get users\n}\n</code></pre>\n<p>But you never share the code inside the loop, which could be why you're having issues. For example, <code>the_author</code> always refers to the author of the current post. If you want to display information about the <code>$user</code>, you would need to pass its ID, or user the public properties, e.g.</p>\n<pre><code>foreach ( $users as $user ) {\n // Get users\n echo esc_html( $user->first_name . ' ' . $user->last_name );\n}\n</code></pre>\n"
}
]
| 2017/12/28 | [
"https://wordpress.stackexchange.com/questions/289666",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/118091/"
]
| When I try to upload any PNG file, I get the following error message:
[](https://i.stack.imgur.com/JYE8w.png)
I have no plugin or anything installed, that could cause this. I even added the following line in order to fix this:
`define('ALLOW_UNFILTERED_UPLOADS', true);`
Since it is a local installation, security is not an issue. But still this didn't fix my problem. Any ideas what could cause this problem? | I think the problem here is that in the process of violating this rule, you've created confusion and problems:
>
> do 1 thing per statement, 1 statement per line
>
>
>
Coupled with another problem:
>
> Passing arrays to the APIs which get stored as serialised PHP ( security issue )
>
>
>
And another:
>
> Always check your assumptions
>
>
> it ignores the users that stored in 'the\_users' user meta and print only current user.
>
>
>
That last one is the killer here. You never check for error values on `get_user_meta`, leading to errors. Users don't start out with `the_users` meta, it has to be added.
Run through this code in your mind, e.g.:
```
$the_following_users = ''; //get_user_meta($the_follower, "the_following_users", true);
if(!in_array($user_follow_to, $the_following_users) && is_array($the_following_users)){
$the_following_users[] = $user_follow_to;
```
Here there is no check on `$the_following_users`, which may not be an array at all, but a `false` or an empty string.
So lets fix the saving:
```
$the_following_users = get_user_meta($the_follower, "the_following_users", true);
if ( empty( $the_following_users ) ) {
$the_following_user = array();
}
```
Then lets simplify the next part:
```
$the_following_users[] = $user_follow_to;
```
And fix the saving so that it's not a security risk:
```
$following = implode( ',', $the_following_users );
update_user_meta($the_follower, "the_following_users", $following );
```
Finally, lets move to the frontend:
Firstly, we assume the `get_user_meta` works, but never check if this is true:
```
$args = array (
'order' => 'DESC',
'include' => get_user_meta($author->ID, 'the_following_users', true)
);
```
What if the user has never followed anybody before? What if they unfollowed everyone? That would break everything! So lets fix that and switch it over to the comma separated list format:
```
$include = get_user_meta($author->ID, 'the_following_users', true);
if ( empty( $include ) ) {
// the user follows nobody, or has not followed anybody yet!
} else {
// turn the string into an array
$include = explode( ',', $include );
$args = array (
'order' => 'DESC',
'include' => $include
);
// etc...
}
```
A Final Note
============
Your loop looks like this:
```
foreach ( $users as $user ) {
// Get users
}
```
But you never share the code inside the loop, which could be why you're having issues. For example, `the_author` always refers to the author of the current post. If you want to display information about the `$user`, you would need to pass its ID, or user the public properties, e.g.
```
foreach ( $users as $user ) {
// Get users
echo esc_html( $user->first_name . ' ' . $user->last_name );
}
``` |
289,690 | <p>I'm trying to figure out how to query posts on a custom post type, using a custom field. </p>
<p>Goal:
On my "artists" single page, I want to display a list of news/album releases for that artist only. Those posts will also show up on the main page. </p>
<p>Concept:<br>
Use a category for each artist on the posts; use a custom field "news_category_slug" on each artist page to link them. I then want to query posts and display all posts in the category that match the custom value "news_category_slug". </p>
<p>Maybe I'm going about this the wrong way; I don't have much PHP knowledge so I'm having trouble figuring out if this is a bad approach or if I just don't understand how to nest a variable inside the query! Help!</p>
| [
{
"answer_id": 289636,
"author": "Nicolai Grossherr",
"author_id": 22534,
"author_profile": "https://wordpress.stackexchange.com/users/22534",
"pm_score": 2,
"selected": false,
"text": "<p>The <code>include</code> parameter of <code>WP_User_Query</code> expects an array as argument. So set the <code>$single</code> parameter of <code>get_user_meta</code> to <code>false</code>. Or don't use it, because <code>false</code> is the default. </p>\n\n<pre><code>// USE\nget_user_meta( $author->ID, 'the_users', false )\n// OR\nget_user_meta( $author->ID, 'the_users' )\n</code></pre>\n"
},
{
"answer_id": 289665,
"author": "Tom J Nowell",
"author_id": 736,
"author_profile": "https://wordpress.stackexchange.com/users/736",
"pm_score": 2,
"selected": true,
"text": "<p>I think the problem here is that in the process of violating this rule, you've created confusion and problems:</p>\n<blockquote>\n<p>do 1 thing per statement, 1 statement per line</p>\n</blockquote>\n<p>Coupled with another problem:</p>\n<blockquote>\n<p>Passing arrays to the APIs which get stored as serialised PHP ( security issue )</p>\n</blockquote>\n<p>And another:</p>\n<blockquote>\n<p>Always check your assumptions</p>\n<p>it ignores the users that stored in 'the_users' user meta and print only current user.</p>\n</blockquote>\n<p>That last one is the killer here. You never check for error values on <code>get_user_meta</code>, leading to errors. Users don't start out with <code>the_users</code> meta, it has to be added.</p>\n<p>Run through this code in your mind, e.g.:</p>\n<pre><code>$the_following_users = ''; //get_user_meta($the_follower, "the_following_users", true);\n\nif(!in_array($user_follow_to, $the_following_users) && is_array($the_following_users)){\n $the_following_users[] = $user_follow_to;\n</code></pre>\n<p>Here there is no check on <code>$the_following_users</code>, which may not be an array at all, but a <code>false</code> or an empty string.</p>\n<p>So lets fix the saving:</p>\n<pre><code>$the_following_users = get_user_meta($the_follower, "the_following_users", true);\nif ( empty( $the_following_users ) ) {\n $the_following_user = array();\n}\n</code></pre>\n<p>Then lets simplify the next part:</p>\n<pre><code>$the_following_users[] = $user_follow_to;\n</code></pre>\n<p>And fix the saving so that it's not a security risk:</p>\n<pre><code>$following = implode( ',', $the_following_users );\nupdate_user_meta($the_follower, "the_following_users", $following );\n</code></pre>\n<p>Finally, lets move to the frontend:</p>\n<p>Firstly, we assume the <code>get_user_meta</code> works, but never check if this is true:</p>\n<pre><code>$args = array (\n 'order' => 'DESC',\n 'include' => get_user_meta($author->ID, 'the_following_users', true)\n);\n</code></pre>\n<p>What if the user has never followed anybody before? What if they unfollowed everyone? That would break everything! So lets fix that and switch it over to the comma separated list format:</p>\n<pre><code>$include = get_user_meta($author->ID, 'the_following_users', true);\nif ( empty( $include ) ) {\n // the user follows nobody, or has not followed anybody yet!\n} else {\n // turn the string into an array\n $include = explode( ',', $include );\n $args = array (\n 'order' => 'DESC',\n 'include' => $include\n );\n // etc...\n}\n</code></pre>\n<h1>A Final Note</h1>\n<p>Your loop looks like this:</p>\n<pre><code>foreach ( $users as $user ) {\n // Get users\n}\n</code></pre>\n<p>But you never share the code inside the loop, which could be why you're having issues. For example, <code>the_author</code> always refers to the author of the current post. If you want to display information about the <code>$user</code>, you would need to pass its ID, or user the public properties, e.g.</p>\n<pre><code>foreach ( $users as $user ) {\n // Get users\n echo esc_html( $user->first_name . ' ' . $user->last_name );\n}\n</code></pre>\n"
}
]
| 2017/12/28 | [
"https://wordpress.stackexchange.com/questions/289690",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/133951/"
]
| I'm trying to figure out how to query posts on a custom post type, using a custom field.
Goal:
On my "artists" single page, I want to display a list of news/album releases for that artist only. Those posts will also show up on the main page.
Concept:
Use a category for each artist on the posts; use a custom field "news\_category\_slug" on each artist page to link them. I then want to query posts and display all posts in the category that match the custom value "news\_category\_slug".
Maybe I'm going about this the wrong way; I don't have much PHP knowledge so I'm having trouble figuring out if this is a bad approach or if I just don't understand how to nest a variable inside the query! Help! | I think the problem here is that in the process of violating this rule, you've created confusion and problems:
>
> do 1 thing per statement, 1 statement per line
>
>
>
Coupled with another problem:
>
> Passing arrays to the APIs which get stored as serialised PHP ( security issue )
>
>
>
And another:
>
> Always check your assumptions
>
>
> it ignores the users that stored in 'the\_users' user meta and print only current user.
>
>
>
That last one is the killer here. You never check for error values on `get_user_meta`, leading to errors. Users don't start out with `the_users` meta, it has to be added.
Run through this code in your mind, e.g.:
```
$the_following_users = ''; //get_user_meta($the_follower, "the_following_users", true);
if(!in_array($user_follow_to, $the_following_users) && is_array($the_following_users)){
$the_following_users[] = $user_follow_to;
```
Here there is no check on `$the_following_users`, which may not be an array at all, but a `false` or an empty string.
So lets fix the saving:
```
$the_following_users = get_user_meta($the_follower, "the_following_users", true);
if ( empty( $the_following_users ) ) {
$the_following_user = array();
}
```
Then lets simplify the next part:
```
$the_following_users[] = $user_follow_to;
```
And fix the saving so that it's not a security risk:
```
$following = implode( ',', $the_following_users );
update_user_meta($the_follower, "the_following_users", $following );
```
Finally, lets move to the frontend:
Firstly, we assume the `get_user_meta` works, but never check if this is true:
```
$args = array (
'order' => 'DESC',
'include' => get_user_meta($author->ID, 'the_following_users', true)
);
```
What if the user has never followed anybody before? What if they unfollowed everyone? That would break everything! So lets fix that and switch it over to the comma separated list format:
```
$include = get_user_meta($author->ID, 'the_following_users', true);
if ( empty( $include ) ) {
// the user follows nobody, or has not followed anybody yet!
} else {
// turn the string into an array
$include = explode( ',', $include );
$args = array (
'order' => 'DESC',
'include' => $include
);
// etc...
}
```
A Final Note
============
Your loop looks like this:
```
foreach ( $users as $user ) {
// Get users
}
```
But you never share the code inside the loop, which could be why you're having issues. For example, `the_author` always refers to the author of the current post. If you want to display information about the `$user`, you would need to pass its ID, or user the public properties, e.g.
```
foreach ( $users as $user ) {
// Get users
echo esc_html( $user->first_name . ' ' . $user->last_name );
}
``` |
289,691 | <p>I tried to remove /category/ base from permalink structure, keeping parent category, but Wordpress gives me back 404 error page.</p>
<p>I'm not using any particular plugin to do that, only using . in category base and using %category%/%postname%/ as permalink structure.</p>
<p>If I restore /category/ base everything works fine. I have already used '/' and '.' to remove category base.</p>
<p>How can I solve the problem? </p>
| [
{
"answer_id": 289636,
"author": "Nicolai Grossherr",
"author_id": 22534,
"author_profile": "https://wordpress.stackexchange.com/users/22534",
"pm_score": 2,
"selected": false,
"text": "<p>The <code>include</code> parameter of <code>WP_User_Query</code> expects an array as argument. So set the <code>$single</code> parameter of <code>get_user_meta</code> to <code>false</code>. Or don't use it, because <code>false</code> is the default. </p>\n\n<pre><code>// USE\nget_user_meta( $author->ID, 'the_users', false )\n// OR\nget_user_meta( $author->ID, 'the_users' )\n</code></pre>\n"
},
{
"answer_id": 289665,
"author": "Tom J Nowell",
"author_id": 736,
"author_profile": "https://wordpress.stackexchange.com/users/736",
"pm_score": 2,
"selected": true,
"text": "<p>I think the problem here is that in the process of violating this rule, you've created confusion and problems:</p>\n<blockquote>\n<p>do 1 thing per statement, 1 statement per line</p>\n</blockquote>\n<p>Coupled with another problem:</p>\n<blockquote>\n<p>Passing arrays to the APIs which get stored as serialised PHP ( security issue )</p>\n</blockquote>\n<p>And another:</p>\n<blockquote>\n<p>Always check your assumptions</p>\n<p>it ignores the users that stored in 'the_users' user meta and print only current user.</p>\n</blockquote>\n<p>That last one is the killer here. You never check for error values on <code>get_user_meta</code>, leading to errors. Users don't start out with <code>the_users</code> meta, it has to be added.</p>\n<p>Run through this code in your mind, e.g.:</p>\n<pre><code>$the_following_users = ''; //get_user_meta($the_follower, "the_following_users", true);\n\nif(!in_array($user_follow_to, $the_following_users) && is_array($the_following_users)){\n $the_following_users[] = $user_follow_to;\n</code></pre>\n<p>Here there is no check on <code>$the_following_users</code>, which may not be an array at all, but a <code>false</code> or an empty string.</p>\n<p>So lets fix the saving:</p>\n<pre><code>$the_following_users = get_user_meta($the_follower, "the_following_users", true);\nif ( empty( $the_following_users ) ) {\n $the_following_user = array();\n}\n</code></pre>\n<p>Then lets simplify the next part:</p>\n<pre><code>$the_following_users[] = $user_follow_to;\n</code></pre>\n<p>And fix the saving so that it's not a security risk:</p>\n<pre><code>$following = implode( ',', $the_following_users );\nupdate_user_meta($the_follower, "the_following_users", $following );\n</code></pre>\n<p>Finally, lets move to the frontend:</p>\n<p>Firstly, we assume the <code>get_user_meta</code> works, but never check if this is true:</p>\n<pre><code>$args = array (\n 'order' => 'DESC',\n 'include' => get_user_meta($author->ID, 'the_following_users', true)\n);\n</code></pre>\n<p>What if the user has never followed anybody before? What if they unfollowed everyone? That would break everything! So lets fix that and switch it over to the comma separated list format:</p>\n<pre><code>$include = get_user_meta($author->ID, 'the_following_users', true);\nif ( empty( $include ) ) {\n // the user follows nobody, or has not followed anybody yet!\n} else {\n // turn the string into an array\n $include = explode( ',', $include );\n $args = array (\n 'order' => 'DESC',\n 'include' => $include\n );\n // etc...\n}\n</code></pre>\n<h1>A Final Note</h1>\n<p>Your loop looks like this:</p>\n<pre><code>foreach ( $users as $user ) {\n // Get users\n}\n</code></pre>\n<p>But you never share the code inside the loop, which could be why you're having issues. For example, <code>the_author</code> always refers to the author of the current post. If you want to display information about the <code>$user</code>, you would need to pass its ID, or user the public properties, e.g.</p>\n<pre><code>foreach ( $users as $user ) {\n // Get users\n echo esc_html( $user->first_name . ' ' . $user->last_name );\n}\n</code></pre>\n"
}
]
| 2017/12/28 | [
"https://wordpress.stackexchange.com/questions/289691",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/103072/"
]
| I tried to remove /category/ base from permalink structure, keeping parent category, but Wordpress gives me back 404 error page.
I'm not using any particular plugin to do that, only using . in category base and using %category%/%postname%/ as permalink structure.
If I restore /category/ base everything works fine. I have already used '/' and '.' to remove category base.
How can I solve the problem? | I think the problem here is that in the process of violating this rule, you've created confusion and problems:
>
> do 1 thing per statement, 1 statement per line
>
>
>
Coupled with another problem:
>
> Passing arrays to the APIs which get stored as serialised PHP ( security issue )
>
>
>
And another:
>
> Always check your assumptions
>
>
> it ignores the users that stored in 'the\_users' user meta and print only current user.
>
>
>
That last one is the killer here. You never check for error values on `get_user_meta`, leading to errors. Users don't start out with `the_users` meta, it has to be added.
Run through this code in your mind, e.g.:
```
$the_following_users = ''; //get_user_meta($the_follower, "the_following_users", true);
if(!in_array($user_follow_to, $the_following_users) && is_array($the_following_users)){
$the_following_users[] = $user_follow_to;
```
Here there is no check on `$the_following_users`, which may not be an array at all, but a `false` or an empty string.
So lets fix the saving:
```
$the_following_users = get_user_meta($the_follower, "the_following_users", true);
if ( empty( $the_following_users ) ) {
$the_following_user = array();
}
```
Then lets simplify the next part:
```
$the_following_users[] = $user_follow_to;
```
And fix the saving so that it's not a security risk:
```
$following = implode( ',', $the_following_users );
update_user_meta($the_follower, "the_following_users", $following );
```
Finally, lets move to the frontend:
Firstly, we assume the `get_user_meta` works, but never check if this is true:
```
$args = array (
'order' => 'DESC',
'include' => get_user_meta($author->ID, 'the_following_users', true)
);
```
What if the user has never followed anybody before? What if they unfollowed everyone? That would break everything! So lets fix that and switch it over to the comma separated list format:
```
$include = get_user_meta($author->ID, 'the_following_users', true);
if ( empty( $include ) ) {
// the user follows nobody, or has not followed anybody yet!
} else {
// turn the string into an array
$include = explode( ',', $include );
$args = array (
'order' => 'DESC',
'include' => $include
);
// etc...
}
```
A Final Note
============
Your loop looks like this:
```
foreach ( $users as $user ) {
// Get users
}
```
But you never share the code inside the loop, which could be why you're having issues. For example, `the_author` always refers to the author of the current post. If you want to display information about the `$user`, you would need to pass its ID, or user the public properties, e.g.
```
foreach ( $users as $user ) {
// Get users
echo esc_html( $user->first_name . ' ' . $user->last_name );
}
``` |
289,735 | <p>Hi i am using the following to modify the results returned from a search on the users tables in wp admin :</p>
<pre><code>add_action('pre_get_users','custom_user_search');
$query->query_vars['meta_query'] = array(
'relation' => 'OR',
array(
'key' => 'billing_postcode',
'value' => str_replace('*', '', $query->query_vars['search']),
'compare' => 'LIKE'
),
</code></pre>
<p>);</p>
<p>This returns the expected results on a standard table load, but when not in conjunction with a search returns an empty set. Can someone explain why this?</p>
| [
{
"answer_id": 289743,
"author": "kierzniak",
"author_id": 132363,
"author_profile": "https://wordpress.stackexchange.com/users/132363",
"pm_score": 0,
"selected": false,
"text": "<p>The query built in this way will search for users by their standard properties <code>AND</code> by this meta field. You want to probably use <code>OR</code> instead of <code>AND</code>.</p>\n\n<p>To debug query results try to find out what SQL it produce.</p>\n\n<pre><code>function wpse_289735_debug_user_query( $query ) {\n\n echo \"SELECT $query->query_fields $query->query_from $query->query_where $query->query_orderby $query->query_limit\";\n die();\n}\n\nadd_filter('pre_user_query', 'wpse_289735_debug_user_query');\n</code></pre>\n\n<p>I could not find any hook which will allow you to modify query to your needs so I crated simple class which will replace SQL directly.</p>\n\n<pre><code>class WPSE_289735_User_Search {\n\n /**\n * Search phrase\n *\n * @var string\n */\n private $search;\n\n /**\n * Class constructor\n */\n public function __construct()\n {\n $this->define_hooks();\n }\n\n /**\n * Filter used to save search phrase and add filter which will replace SQL\n */\n public function add_custom_search_filter( $query ) {\n\n if( isset( $query->query_vars['search'] ) && !empty( $query->query_vars['search'] ) ) {\n\n /**\n * Save search phrase\n */\n $this->search = str_replace('*', '', $query->query_vars['search']);\n\n /**\n * Add filter only when searching users\n */\n add_filter( 'query', array($this, 'replace_user_search_sql') );\n }\n }\n\n /**\n * Replace user search SQL with own SQL\n */\n public function replace_user_search_sql( $query ) {\n\n /**\n * Immediately remove filter to not break other queries\n */\n remove_filter( 'query', array($this, 'replace_user_search_sql') );\n\n global $wpdb;\n\n $sql[] = \"SELECT DISTINCT SQL_CALC_FOUND_ROWS $wpdb->users.ID\";\n $sql[] = \"FROM $wpdb->users\";\n $sql[] = \"INNER JOIN $wpdb->usermeta ON ($wpdb->users.ID = $wpdb->usermeta.user_id)\";\n\n $sql[] = \"WHERE 1=1\";\n\n $sql[] = \"AND\";\n $sql[] = \"(\";\n $sql[] = \"($wpdb->usermeta.meta_key = 'billing_postcode' AND $wpdb->usermeta.meta_value LIKE '%s')\";\n $sql[] = \"OR\";\n $sql[] = \"($wpdb->users.user_login LIKE '%s' OR $wpdb->users.user_url LIKE '%s' OR $wpdb->users.user_email LIKE '%s' OR $wpdb->users.user_nicename LIKE '%s' OR $wpdb->users.display_name LIKE '%s')\";\n $sql[] = \")\";\n\n $sql[] = \"ORDER BY $wpdb->users.user_login ASC LIMIT 0, 20\";\n\n return $wpdb->prepare( join(\" \", $sql), $this->search, $this->search, $this->search, $this->search, $this->search, $this->search );\n }\n\n /**\n * Define plugin related hooks\n */\n private function define_hooks() {\n\n /**\n * Filter used to save search phrase and add filter which will replace SQL\n */\n add_action('pre_get_users', array( $this, 'add_custom_search_filter'));\n }\n}\n\nnew WPSE_289735_User_Search();\n</code></pre>\n"
},
{
"answer_id": 289753,
"author": "frank astin",
"author_id": 101873,
"author_profile": "https://wordpress.stackexchange.com/users/101873",
"pm_score": 1,
"selected": false,
"text": "<p>OK, Here's how I did it :</p>\n\n<pre><code>add_action('pre_user_query', 'custom_user_list_queries');\n\nfunction custom_user_list_queries($query){ \n\nif(!empty($query->query_vars['search'])) {\n $query->query_from .= \" LEFT OUTER JOIN wp_usermeta AS alias ON (wp_users.ID = alias.user_id)\";//note use of alias\n $query->query_where .= \" OR \".\n \"(alias.meta_key = 'billing_postcode' AND alias.meta_value LIKE '%\".$query->query_vars['search'].\"%') \".\n \" OR \".\n \"(alias.meta_key = 'first_name' AND alias.meta_value LIKE '%\".$query->query_vars['search'].\"%') \".\n \" OR \".\n \"(alias.meta_key = 'last_name' AND alias.meta_value LIKE '%\".$query->query_vars['search'].\"%') \".\n \" OR \".\n \"(alias.meta_key = 'chat_name' AND alias.meta_value LIKE '%\".$query->query_vars['search'].\"%') \";\n}\n\n}\n</code></pre>\n"
}
]
| 2017/12/29 | [
"https://wordpress.stackexchange.com/questions/289735",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/101873/"
]
| Hi i am using the following to modify the results returned from a search on the users tables in wp admin :
```
add_action('pre_get_users','custom_user_search');
$query->query_vars['meta_query'] = array(
'relation' => 'OR',
array(
'key' => 'billing_postcode',
'value' => str_replace('*', '', $query->query_vars['search']),
'compare' => 'LIKE'
),
```
);
This returns the expected results on a standard table load, but when not in conjunction with a search returns an empty set. Can someone explain why this? | OK, Here's how I did it :
```
add_action('pre_user_query', 'custom_user_list_queries');
function custom_user_list_queries($query){
if(!empty($query->query_vars['search'])) {
$query->query_from .= " LEFT OUTER JOIN wp_usermeta AS alias ON (wp_users.ID = alias.user_id)";//note use of alias
$query->query_where .= " OR ".
"(alias.meta_key = 'billing_postcode' AND alias.meta_value LIKE '%".$query->query_vars['search']."%') ".
" OR ".
"(alias.meta_key = 'first_name' AND alias.meta_value LIKE '%".$query->query_vars['search']."%') ".
" OR ".
"(alias.meta_key = 'last_name' AND alias.meta_value LIKE '%".$query->query_vars['search']."%') ".
" OR ".
"(alias.meta_key = 'chat_name' AND alias.meta_value LIKE '%".$query->query_vars['search']."%') ";
}
}
``` |
289,749 | <p>It is possible to change colors of <a href="https://developer.wordpress.org/resource/dashicons/#chart-bar" rel="nofollow noreferrer">DashIcons</a> with CSS? I couldnt get it to work.</p>
| [
{
"answer_id": 289752,
"author": "DekiGk",
"author_id": 69750,
"author_profile": "https://wordpress.stackexchange.com/users/69750",
"pm_score": 4,
"selected": true,
"text": "<p>Yes, this is possible. Make sure your CSS selector is correct. You can target the specific HTML element or its <code>::before</code> pseudo element and change colour with CSS. Can you post your HTML snippet of the element you want to change and the CSS selector you are using? Maybe you mean to change the colour inside WP admin area for all dash-icons? In that case:</p>\n\n<pre><code>.dashicons { color: red; }\n</code></pre>\n"
},
{
"answer_id": 367874,
"author": "Tia P",
"author_id": 189083,
"author_profile": "https://wordpress.stackexchange.com/users/189083",
"pm_score": 2,
"selected": false,
"text": "<p>The correct way:</p>\n\n<pre><code>#adminmenu div.wp-menu-image:before {\n color: #000; <-- here\n}\n\n#adminmenu .wp-has-current-submenu div.wp-menu-image:before {\n color: #000; <-- here\n}\n</code></pre>\n\n<p>And to make sure you get the hover state of the selected submenu</p>\n\n<pre><code>#adminmenu li.wp-has-current-submenu:hover div.wp-menu-image:before,\n#adminmenu .wp-has-current-submenu div.wp-menu-image:before,\n#adminmenu .current div.wp-menu-image:before,\n#adminmenu a.wp-has-current-submenu:hover div.wp-menu-image:before,\n#adminmenu a.current:hover div.wp-menu-image:before,\n#adminmenu li.wp-has-current-submenu a:focus div.wp-menu-image:before,\n#adminmenu li.wp-has-current-submenu.opensub div.wp-menu-image:before {\n color: #000; <-- here\n}\n</code></pre>\n\n<p>All of the dashicon css and the related wp-menu-image css is in the admin-menu.css sheet.</p>\n"
}
]
| 2017/12/29 | [
"https://wordpress.stackexchange.com/questions/289749",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/33667/"
]
| It is possible to change colors of [DashIcons](https://developer.wordpress.org/resource/dashicons/#chart-bar) with CSS? I couldnt get it to work. | Yes, this is possible. Make sure your CSS selector is correct. You can target the specific HTML element or its `::before` pseudo element and change colour with CSS. Can you post your HTML snippet of the element you want to change and the CSS selector you are using? Maybe you mean to change the colour inside WP admin area for all dash-icons? In that case:
```
.dashicons { color: red; }
``` |
289,759 | <p>Found this and it works, but want to change the 10 MB limit to 5 GB.</p>
<pre><code>$upload_bytes_limit_reached = ( ( $filesize + $upload_bytes ) > ( 1024 * 1024 * 10 ) );
</code></pre>
<hr>
<pre><code>add_filter( 'wp_handle_upload', 'wpse47580_update_upload_stats' );
function wpse47580_update_upload_stats( $args ) {
$size = filesize( $args['file'] );
$user_id = get_current_user_id();
$upload_count = get_user_meta( $user_id, 'upload_count', true );
$upload_bytes = get_user_meta( $user_id, 'upload_bytes', true );
update_user_meta( $user_id, 'upload_count', $upload_count + 1 );
update_user_meta( $user_id, 'upload_bytes', $upload_bytes + $size );
}
</code></pre>
<h1>This function runs before the file is uploaded.</h1>
<pre><code>add_filter( 'wp_handle_upload_prefilter', 'wpse47580_check_upload_limits' );
function wpse47580_check_upload_limits( $file ) {
$user_id = get_current_user_id();
$upload_count = get_user_meta( $user_id, 'upload_count', true );
$upload_bytes = get_user_meta( $user_id, 'upload_bytes', true );
$filesize = $file['size']; // bytes
$upload_bytes_limit_reached = ( ( $filesize + $upload_bytes ) > ( 1024 * 1024 * 10 ) );
$upload_count_limit_reached = ( $upload_count + 1 ) > 100;
if ( $upload_count_limit_reached || $upload_bytes_limit_reached )
$file['error'] = 'Upload limit has been reached for this account!';
return $file;
}
</code></pre>
| [
{
"answer_id": 289765,
"author": "Nicolai Grossherr",
"author_id": 22534,
"author_profile": "https://wordpress.stackexchange.com/users/22534",
"pm_score": 2,
"selected": false,
"text": "<p>You have to set <a href=\"https://wordpress.stackexchange.com/questions/252849/wordpress-media-upload-limit\">PHP upload limits</a> properly.</p>\n\n<p>Calculating 5 GB in Bytes would look like:</p>\n\n<pre><code>$5GBinBytes = 1024 * 1024 * 1024 * 5;\n// or nicer\n$5GBinBytes = pow( 1024, 3 ) * 5;\n</code></pre>\n\n<p>5GB is a lot of data, which might take some time. There is a good chance you have to crank up process time limits β <code>max_execution_time</code> and <code>max_input_time</code> come to mind β and <code>memory_limit</code> as well.</p>\n\n<p>As per comment by @swissspidy, WordPress defines the constant <code>GB_IN_BYTES</code>, usage:</p>\n\n<pre><code>$5GBinBytes = GB_IN_BYTES * 5;\n</code></pre>\n"
},
{
"answer_id": 291736,
"author": "Darren Cain",
"author_id": 133947,
"author_profile": "https://wordpress.stackexchange.com/users/133947",
"pm_score": 1,
"selected": true,
"text": "<p>I have it working. I removed the top half of the script. Don't know why it now works, but tested it and does what I wanted. Thanks for all your help and support. The original thread can be found <a href=\"https://wordpress.stackexchange.com/q/47580/22534\">here</a>, for those interested.</p>\n\n<pre><code>add_filter( 'wp_handle_upload_prefilter', 'wpse47580_check_upload_limits' );\nfunction wpse47580_check_upload_limits( $file ) {\n $user_id = get_current_user_id();\n\n $upload_bytes = get_user_meta( $user_id, 'upload_bytes', true );\n\n $filesize = $file['size']; // bytes\n\n $upload_bytes_limit_reached = ( ( $filesize + $upload_bytes ) > ( GB_IN_BYTES * 5 ) );\n\n if ( $upload_bytes_limit_reached )\n $file['error'] = 'Upload limit has been reached for this account!';\n\n return $file;\n}\n</code></pre>\n"
}
]
| 2017/12/29 | [
"https://wordpress.stackexchange.com/questions/289759",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/133947/"
]
| Found this and it works, but want to change the 10 MB limit to 5 GB.
```
$upload_bytes_limit_reached = ( ( $filesize + $upload_bytes ) > ( 1024 * 1024 * 10 ) );
```
---
```
add_filter( 'wp_handle_upload', 'wpse47580_update_upload_stats' );
function wpse47580_update_upload_stats( $args ) {
$size = filesize( $args['file'] );
$user_id = get_current_user_id();
$upload_count = get_user_meta( $user_id, 'upload_count', true );
$upload_bytes = get_user_meta( $user_id, 'upload_bytes', true );
update_user_meta( $user_id, 'upload_count', $upload_count + 1 );
update_user_meta( $user_id, 'upload_bytes', $upload_bytes + $size );
}
```
This function runs before the file is uploaded.
===============================================
```
add_filter( 'wp_handle_upload_prefilter', 'wpse47580_check_upload_limits' );
function wpse47580_check_upload_limits( $file ) {
$user_id = get_current_user_id();
$upload_count = get_user_meta( $user_id, 'upload_count', true );
$upload_bytes = get_user_meta( $user_id, 'upload_bytes', true );
$filesize = $file['size']; // bytes
$upload_bytes_limit_reached = ( ( $filesize + $upload_bytes ) > ( 1024 * 1024 * 10 ) );
$upload_count_limit_reached = ( $upload_count + 1 ) > 100;
if ( $upload_count_limit_reached || $upload_bytes_limit_reached )
$file['error'] = 'Upload limit has been reached for this account!';
return $file;
}
``` | I have it working. I removed the top half of the script. Don't know why it now works, but tested it and does what I wanted. Thanks for all your help and support. The original thread can be found [here](https://wordpress.stackexchange.com/q/47580/22534), for those interested.
```
add_filter( 'wp_handle_upload_prefilter', 'wpse47580_check_upload_limits' );
function wpse47580_check_upload_limits( $file ) {
$user_id = get_current_user_id();
$upload_bytes = get_user_meta( $user_id, 'upload_bytes', true );
$filesize = $file['size']; // bytes
$upload_bytes_limit_reached = ( ( $filesize + $upload_bytes ) > ( GB_IN_BYTES * 5 ) );
if ( $upload_bytes_limit_reached )
$file['error'] = 'Upload limit has been reached for this account!';
return $file;
}
``` |
289,763 | <p>I am using the Enhanced Image Library plugin to automatically add a taxonomy to images uploaded to a custom post type. The plugin has a feature that will allow the post's categories to be automatically added to associated images when the image is uploaded.</p>
<p>However, if the post category is not assigned to the post before the images are added, then the images will not be categorized correctly. The easiest solution would be if there was a way to assign a default category directly after the "New Post" button was clicked, before the user has a chance to input any data into the post fields, and well before the save_post action.</p>
<p>All of the answers to this question that I found seem to reference the save_post or publish_post actions. Is there any action that can be utilized when "new post" is initially clicked?</p>
<p>If there is not, do you have any other suggestions? Should I attempt to add javascript somewhere to pre-check this field in a post admin template? If so, where should I find that?</p>
| [
{
"answer_id": 289765,
"author": "Nicolai Grossherr",
"author_id": 22534,
"author_profile": "https://wordpress.stackexchange.com/users/22534",
"pm_score": 2,
"selected": false,
"text": "<p>You have to set <a href=\"https://wordpress.stackexchange.com/questions/252849/wordpress-media-upload-limit\">PHP upload limits</a> properly.</p>\n\n<p>Calculating 5 GB in Bytes would look like:</p>\n\n<pre><code>$5GBinBytes = 1024 * 1024 * 1024 * 5;\n// or nicer\n$5GBinBytes = pow( 1024, 3 ) * 5;\n</code></pre>\n\n<p>5GB is a lot of data, which might take some time. There is a good chance you have to crank up process time limits β <code>max_execution_time</code> and <code>max_input_time</code> come to mind β and <code>memory_limit</code> as well.</p>\n\n<p>As per comment by @swissspidy, WordPress defines the constant <code>GB_IN_BYTES</code>, usage:</p>\n\n<pre><code>$5GBinBytes = GB_IN_BYTES * 5;\n</code></pre>\n"
},
{
"answer_id": 291736,
"author": "Darren Cain",
"author_id": 133947,
"author_profile": "https://wordpress.stackexchange.com/users/133947",
"pm_score": 1,
"selected": true,
"text": "<p>I have it working. I removed the top half of the script. Don't know why it now works, but tested it and does what I wanted. Thanks for all your help and support. The original thread can be found <a href=\"https://wordpress.stackexchange.com/q/47580/22534\">here</a>, for those interested.</p>\n\n<pre><code>add_filter( 'wp_handle_upload_prefilter', 'wpse47580_check_upload_limits' );\nfunction wpse47580_check_upload_limits( $file ) {\n $user_id = get_current_user_id();\n\n $upload_bytes = get_user_meta( $user_id, 'upload_bytes', true );\n\n $filesize = $file['size']; // bytes\n\n $upload_bytes_limit_reached = ( ( $filesize + $upload_bytes ) > ( GB_IN_BYTES * 5 ) );\n\n if ( $upload_bytes_limit_reached )\n $file['error'] = 'Upload limit has been reached for this account!';\n\n return $file;\n}\n</code></pre>\n"
}
]
| 2017/12/29 | [
"https://wordpress.stackexchange.com/questions/289763",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/134003/"
]
| I am using the Enhanced Image Library plugin to automatically add a taxonomy to images uploaded to a custom post type. The plugin has a feature that will allow the post's categories to be automatically added to associated images when the image is uploaded.
However, if the post category is not assigned to the post before the images are added, then the images will not be categorized correctly. The easiest solution would be if there was a way to assign a default category directly after the "New Post" button was clicked, before the user has a chance to input any data into the post fields, and well before the save\_post action.
All of the answers to this question that I found seem to reference the save\_post or publish\_post actions. Is there any action that can be utilized when "new post" is initially clicked?
If there is not, do you have any other suggestions? Should I attempt to add javascript somewhere to pre-check this field in a post admin template? If so, where should I find that? | I have it working. I removed the top half of the script. Don't know why it now works, but tested it and does what I wanted. Thanks for all your help and support. The original thread can be found [here](https://wordpress.stackexchange.com/q/47580/22534), for those interested.
```
add_filter( 'wp_handle_upload_prefilter', 'wpse47580_check_upload_limits' );
function wpse47580_check_upload_limits( $file ) {
$user_id = get_current_user_id();
$upload_bytes = get_user_meta( $user_id, 'upload_bytes', true );
$filesize = $file['size']; // bytes
$upload_bytes_limit_reached = ( ( $filesize + $upload_bytes ) > ( GB_IN_BYTES * 5 ) );
if ( $upload_bytes_limit_reached )
$file['error'] = 'Upload limit has been reached for this account!';
return $file;
}
``` |
289,769 | <p>In the WooCommerce plugin, the PayPal gateway has recently been updated to capture payment on status change TO either "Processing" or "Completed".</p>
<p>We want to ONLY allow capture after order status has been updated to COMPLETED.</p>
<p>In order to do this, I have identified that I need to remove an action. The action is location in class-wc-gateway-paypal.php and the code is below:</p>
<pre><code>class WC_Gateway_Paypal extends WC_Payment_Gateway {
/** @var bool Whether or not logging is enabled */
public static $log_enabled = false;
/** @var WC_Logger Logger instance */
public static $log = false;
/**
* Constructor for the gateway.
*/
public function __construct() {
$this->id = 'paypal';
$this->has_fields = false;
$this->order_button_text = __( 'Proceed to PayPal', 'woocommerce' );
$this->method_title = __( 'PayPal', 'woocommerce' );
$this->method_description = sprintf( __( 'PayPal Standard sends customers to PayPal to enter their payment information. PayPal IPN requires fsockopen/cURL support to update order statuses after payment. Check the <a href="%s">system status</a> page for more details.', 'woocommerce' ), admin_url( 'admin.php?page=wc-status' ) );
$this->supports = array(
'products',
'refunds',
);
// Load the settings.
$this->init_form_fields();
$this->init_settings();
// Define user set variables.
$this->title = $this->get_option( 'title' );
$this->description = $this->get_option( 'description' );
$this->testmode = 'yes' === $this->get_option( 'testmode', 'no' );
$this->debug = 'yes' === $this->get_option( 'debug', 'no' );
$this->email = $this->get_option( 'email' );
$this->receiver_email = $this->get_option( 'receiver_email', $this->email );
$this->identity_token = $this->get_option( 'identity_token' );
self::$log_enabled = $this->debug;
add_action( 'woocommerce_update_options_payment_gateways_' . $this->id, array( $this, 'process_admin_options' ) );
add_action( 'woocommerce_order_status_on-hold_to_processing', array( $this, 'capture_payment' ) );
</code></pre>
<p>The final line is the action I want to remove. </p>
<pre><code>add_action( 'woocommerce_order_status_on-hold_to_processing', array( $this, 'capture_payment' ) );
</code></pre>
<p>I have my own plugin that I use to call various functions with. Before I screw something up, I am hoping someone can validate (or correct) the code I plan to use:</p>
<pre><code>add_action( 'woocommerce_order_status_on-hold_to_completed','remove_PaypalCapture_action' );
function remove_PaypalCapture_action(){
global $WC_Gateway_Paypal; //get access to the class object instance
remove_action('woocommerce_order_status_on-hold_to_processing', array($WC_Gateway_Paypal, 'capture_payment' )); //DO NOT capture payment upon order change to processing
}
</code></pre>
<p>Will this work, or am I missing something?</p>
| [
{
"answer_id": 289780,
"author": "Frank P. Walentynowicz",
"author_id": 32851,
"author_profile": "https://wordpress.stackexchange.com/users/32851",
"pm_score": 0,
"selected": false,
"text": "<p>If <em>WooCommerce</em> plugin declares <code>$WC_Gateway_Paypal</code> as global variable:</p>\n\n<pre><code>global $WC_Gateway_Paypal;\n</code></pre>\n\n<p>and instantiates <code>WC_Gateway_Paypal class</code> as:</p>\n\n<pre><code>$WC_Gateway_Paypal = new WC_Gateway_Paypal;\n</code></pre>\n\n<p>then, yes, the code below:</p>\n\n<pre><code>global $WC_Gateway_Paypal;\nremove_action('woocommerce_order_status_on-hold_to_processing', array($WC_Gateway_Paypal, 'capture_payment'), 10);\n</code></pre>\n\n<p>will properly remove this action.</p>\n\n<blockquote>\n <p><strong>Note</strong>: <code>remove_action()</code> must be called inside a function and cannot be called directly in your plugin or theme ( <em>from Codex</em> ).</p>\n</blockquote>\n"
},
{
"answer_id": 289841,
"author": "Nathan Johnson",
"author_id": 106269,
"author_profile": "https://wordpress.stackexchange.com/users/106269",
"pm_score": 1,
"selected": false,
"text": "<p>There are two things that you'll need in order to remove the action.</p>\n\n<ol>\n<li>The exact instance of WC_Gateway_Paypal</li>\n<li>Knowing when the action is added and when it is executed</li>\n</ol>\n\n<p>Without these, it will be difficult, but impossible to remove the action. Getting the instance of WC_Gateway_Paypal should be straightforward.</p>\n\n<pre><code>//* Make sure class-wc-payment-gateways.php is included once\ninclude_once PATH_TO . class-wc-payment-gateways.php;\n\n//* Get the gateways\n$gateways = \\WC_Payment_Gateways::instance();\n\n//* The class instances are located in the payment_gateways property\n$gateways->payment_gateways\n</code></pre>\n\n<p><strike>The Paypal gateway instance should be in this array. I don't have WooCommerce installed on this machine right now, so I don't know exactly how it's stored. But you should be able to figure it out.</strike></p>\n\n<p>[Added: Thanks to @willington-vega for finding out how WC stores the payment gateways in the array. I've updated the <code>get_wc_paypal_payment_gateway()</code> function below with this.]</p>\n\n<p>Fortunately, the action is added at priority 10 to the <code>woocommerce_order_status_on-hold_to_completed</code> hook. What we can do is hook in at an earlier priority and remove the hook.</p>\n\n<pre><code>add_action( 'woocommerce_order_status_on-hold_to_completed', 'remove_PaypalCapture_action', 9 );\nfunction remove_PaypalCapture_action() {\n //* This is where we'll remove the action\n\n //* Get the instance\n $WC_Paypal_Payment_Gateway = get_wc_paypal_payment_gateway();\n remove_action( 'woocommerce_order_status_on-hold_to_completed', [ $WC_Paypal_Payment_Gateway , 'capture_payment' ] );\n}\nfunction get_wc_paypal_payment_gateway() {\n\n //* Make sure class-wc-payment-gateways.php is included once\n include_once PATH_TO . class-wc-payment-gateways.php;\n\n //* Return the paypal gateway\n return \\WC_Payment_Gateways::instance()->payment_gateways[ 'paypal' ];\n}\n</code></pre>\n"
}
]
| 2017/12/30 | [
"https://wordpress.stackexchange.com/questions/289769",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/134005/"
]
| In the WooCommerce plugin, the PayPal gateway has recently been updated to capture payment on status change TO either "Processing" or "Completed".
We want to ONLY allow capture after order status has been updated to COMPLETED.
In order to do this, I have identified that I need to remove an action. The action is location in class-wc-gateway-paypal.php and the code is below:
```
class WC_Gateway_Paypal extends WC_Payment_Gateway {
/** @var bool Whether or not logging is enabled */
public static $log_enabled = false;
/** @var WC_Logger Logger instance */
public static $log = false;
/**
* Constructor for the gateway.
*/
public function __construct() {
$this->id = 'paypal';
$this->has_fields = false;
$this->order_button_text = __( 'Proceed to PayPal', 'woocommerce' );
$this->method_title = __( 'PayPal', 'woocommerce' );
$this->method_description = sprintf( __( 'PayPal Standard sends customers to PayPal to enter their payment information. PayPal IPN requires fsockopen/cURL support to update order statuses after payment. Check the <a href="%s">system status</a> page for more details.', 'woocommerce' ), admin_url( 'admin.php?page=wc-status' ) );
$this->supports = array(
'products',
'refunds',
);
// Load the settings.
$this->init_form_fields();
$this->init_settings();
// Define user set variables.
$this->title = $this->get_option( 'title' );
$this->description = $this->get_option( 'description' );
$this->testmode = 'yes' === $this->get_option( 'testmode', 'no' );
$this->debug = 'yes' === $this->get_option( 'debug', 'no' );
$this->email = $this->get_option( 'email' );
$this->receiver_email = $this->get_option( 'receiver_email', $this->email );
$this->identity_token = $this->get_option( 'identity_token' );
self::$log_enabled = $this->debug;
add_action( 'woocommerce_update_options_payment_gateways_' . $this->id, array( $this, 'process_admin_options' ) );
add_action( 'woocommerce_order_status_on-hold_to_processing', array( $this, 'capture_payment' ) );
```
The final line is the action I want to remove.
```
add_action( 'woocommerce_order_status_on-hold_to_processing', array( $this, 'capture_payment' ) );
```
I have my own plugin that I use to call various functions with. Before I screw something up, I am hoping someone can validate (or correct) the code I plan to use:
```
add_action( 'woocommerce_order_status_on-hold_to_completed','remove_PaypalCapture_action' );
function remove_PaypalCapture_action(){
global $WC_Gateway_Paypal; //get access to the class object instance
remove_action('woocommerce_order_status_on-hold_to_processing', array($WC_Gateway_Paypal, 'capture_payment' )); //DO NOT capture payment upon order change to processing
}
```
Will this work, or am I missing something? | There are two things that you'll need in order to remove the action.
1. The exact instance of WC\_Gateway\_Paypal
2. Knowing when the action is added and when it is executed
Without these, it will be difficult, but impossible to remove the action. Getting the instance of WC\_Gateway\_Paypal should be straightforward.
```
//* Make sure class-wc-payment-gateways.php is included once
include_once PATH_TO . class-wc-payment-gateways.php;
//* Get the gateways
$gateways = \WC_Payment_Gateways::instance();
//* The class instances are located in the payment_gateways property
$gateways->payment_gateways
```
The Paypal gateway instance should be in this array. I don't have WooCommerce installed on this machine right now, so I don't know exactly how it's stored. But you should be able to figure it out.
[Added: Thanks to @willington-vega for finding out how WC stores the payment gateways in the array. I've updated the `get_wc_paypal_payment_gateway()` function below with this.]
Fortunately, the action is added at priority 10 to the `woocommerce_order_status_on-hold_to_completed` hook. What we can do is hook in at an earlier priority and remove the hook.
```
add_action( 'woocommerce_order_status_on-hold_to_completed', 'remove_PaypalCapture_action', 9 );
function remove_PaypalCapture_action() {
//* This is where we'll remove the action
//* Get the instance
$WC_Paypal_Payment_Gateway = get_wc_paypal_payment_gateway();
remove_action( 'woocommerce_order_status_on-hold_to_completed', [ $WC_Paypal_Payment_Gateway , 'capture_payment' ] );
}
function get_wc_paypal_payment_gateway() {
//* Make sure class-wc-payment-gateways.php is included once
include_once PATH_TO . class-wc-payment-gateways.php;
//* Return the paypal gateway
return \WC_Payment_Gateways::instance()->payment_gateways[ 'paypal' ];
}
``` |
289,794 | <p>I'm trying to redirect the user to a "Thank you for signing up" page but I can not get it.</p>
<p>This is the code (It's wrong)</p>
<pre><code>function tml_action_url( $url, $action, $instance ) {
if ( 'login' == $action )
$url = 'url/thanks';
return $url;
}
add_filter( 'tml_action_url', 'tml_action_url', 10, 3 );
?>
</code></pre>
<p>But it does not work as I want.</p>
<p>Once the user registers, he takes me to the url:</p>
<p>url/?checkemail=registered</p>
<p>I do not know how to reference it.</p>
<p>Any ideas?</p>
<p>Greetings, thank you.</p>
| [
{
"answer_id": 289780,
"author": "Frank P. Walentynowicz",
"author_id": 32851,
"author_profile": "https://wordpress.stackexchange.com/users/32851",
"pm_score": 0,
"selected": false,
"text": "<p>If <em>WooCommerce</em> plugin declares <code>$WC_Gateway_Paypal</code> as global variable:</p>\n\n<pre><code>global $WC_Gateway_Paypal;\n</code></pre>\n\n<p>and instantiates <code>WC_Gateway_Paypal class</code> as:</p>\n\n<pre><code>$WC_Gateway_Paypal = new WC_Gateway_Paypal;\n</code></pre>\n\n<p>then, yes, the code below:</p>\n\n<pre><code>global $WC_Gateway_Paypal;\nremove_action('woocommerce_order_status_on-hold_to_processing', array($WC_Gateway_Paypal, 'capture_payment'), 10);\n</code></pre>\n\n<p>will properly remove this action.</p>\n\n<blockquote>\n <p><strong>Note</strong>: <code>remove_action()</code> must be called inside a function and cannot be called directly in your plugin or theme ( <em>from Codex</em> ).</p>\n</blockquote>\n"
},
{
"answer_id": 289841,
"author": "Nathan Johnson",
"author_id": 106269,
"author_profile": "https://wordpress.stackexchange.com/users/106269",
"pm_score": 1,
"selected": false,
"text": "<p>There are two things that you'll need in order to remove the action.</p>\n\n<ol>\n<li>The exact instance of WC_Gateway_Paypal</li>\n<li>Knowing when the action is added and when it is executed</li>\n</ol>\n\n<p>Without these, it will be difficult, but impossible to remove the action. Getting the instance of WC_Gateway_Paypal should be straightforward.</p>\n\n<pre><code>//* Make sure class-wc-payment-gateways.php is included once\ninclude_once PATH_TO . class-wc-payment-gateways.php;\n\n//* Get the gateways\n$gateways = \\WC_Payment_Gateways::instance();\n\n//* The class instances are located in the payment_gateways property\n$gateways->payment_gateways\n</code></pre>\n\n<p><strike>The Paypal gateway instance should be in this array. I don't have WooCommerce installed on this machine right now, so I don't know exactly how it's stored. But you should be able to figure it out.</strike></p>\n\n<p>[Added: Thanks to @willington-vega for finding out how WC stores the payment gateways in the array. I've updated the <code>get_wc_paypal_payment_gateway()</code> function below with this.]</p>\n\n<p>Fortunately, the action is added at priority 10 to the <code>woocommerce_order_status_on-hold_to_completed</code> hook. What we can do is hook in at an earlier priority and remove the hook.</p>\n\n<pre><code>add_action( 'woocommerce_order_status_on-hold_to_completed', 'remove_PaypalCapture_action', 9 );\nfunction remove_PaypalCapture_action() {\n //* This is where we'll remove the action\n\n //* Get the instance\n $WC_Paypal_Payment_Gateway = get_wc_paypal_payment_gateway();\n remove_action( 'woocommerce_order_status_on-hold_to_completed', [ $WC_Paypal_Payment_Gateway , 'capture_payment' ] );\n}\nfunction get_wc_paypal_payment_gateway() {\n\n //* Make sure class-wc-payment-gateways.php is included once\n include_once PATH_TO . class-wc-payment-gateways.php;\n\n //* Return the paypal gateway\n return \\WC_Payment_Gateways::instance()->payment_gateways[ 'paypal' ];\n}\n</code></pre>\n"
}
]
| 2017/12/30 | [
"https://wordpress.stackexchange.com/questions/289794",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/134019/"
]
| I'm trying to redirect the user to a "Thank you for signing up" page but I can not get it.
This is the code (It's wrong)
```
function tml_action_url( $url, $action, $instance ) {
if ( 'login' == $action )
$url = 'url/thanks';
return $url;
}
add_filter( 'tml_action_url', 'tml_action_url', 10, 3 );
?>
```
But it does not work as I want.
Once the user registers, he takes me to the url:
url/?checkemail=registered
I do not know how to reference it.
Any ideas?
Greetings, thank you. | There are two things that you'll need in order to remove the action.
1. The exact instance of WC\_Gateway\_Paypal
2. Knowing when the action is added and when it is executed
Without these, it will be difficult, but impossible to remove the action. Getting the instance of WC\_Gateway\_Paypal should be straightforward.
```
//* Make sure class-wc-payment-gateways.php is included once
include_once PATH_TO . class-wc-payment-gateways.php;
//* Get the gateways
$gateways = \WC_Payment_Gateways::instance();
//* The class instances are located in the payment_gateways property
$gateways->payment_gateways
```
The Paypal gateway instance should be in this array. I don't have WooCommerce installed on this machine right now, so I don't know exactly how it's stored. But you should be able to figure it out.
[Added: Thanks to @willington-vega for finding out how WC stores the payment gateways in the array. I've updated the `get_wc_paypal_payment_gateway()` function below with this.]
Fortunately, the action is added at priority 10 to the `woocommerce_order_status_on-hold_to_completed` hook. What we can do is hook in at an earlier priority and remove the hook.
```
add_action( 'woocommerce_order_status_on-hold_to_completed', 'remove_PaypalCapture_action', 9 );
function remove_PaypalCapture_action() {
//* This is where we'll remove the action
//* Get the instance
$WC_Paypal_Payment_Gateway = get_wc_paypal_payment_gateway();
remove_action( 'woocommerce_order_status_on-hold_to_completed', [ $WC_Paypal_Payment_Gateway , 'capture_payment' ] );
}
function get_wc_paypal_payment_gateway() {
//* Make sure class-wc-payment-gateways.php is included once
include_once PATH_TO . class-wc-payment-gateways.php;
//* Return the paypal gateway
return \WC_Payment_Gateways::instance()->payment_gateways[ 'paypal' ];
}
``` |
289,812 | <p>I've never thought to do this with WordPress until now, but I was wondering is it possible for two templates to be chosen to create a post or page in WordPress?</p>
<p>When you are on the 'Edit Page' there is the 'Page Attributes>Template' section. When a custom template is chosen that will generate the main layout of the page which includes the region for an <code>iframe</code>. The <code>iframe</code> comes into play when the <code>custom-field</code> below the content editor is filled out, which would automatically call the second custom template when the page is published.</p>
<p>So basically, for the sake of a visual, imagine a comparison site with side-by-side view of two pages. Only now think of that example as a side-by-side view of data inputted into <code>the_content</code> (WP content editor) and <code>custom_field</code> (custom field box/field below the WP content editor).</p>
<p>The <code>iframe</code> is needed, but if you know what other code could be used to produce the same results would be fine.</p>
| [
{
"answer_id": 289833,
"author": "admcfajn",
"author_id": 123674,
"author_profile": "https://wordpress.stackexchange.com/users/123674",
"pm_score": 1,
"selected": false,
"text": "<p>No, you would not use two page-templates on a single page.</p>\n\n<p>Yes, you can have a different admin-page layout / configuration for different page-templates. </p>\n\n<p>Page-template-A could have two post-editors and page-template-B (or post-format for that matter) could have only a name, email, and featured-image.</p>\n\n<p>You could use a single page template and separate includes to help organize your code.</p>\n\n<pre><code><?php\n// Template Name: 289812\n?>\n<div class=\"page-tpl-289812\">\n <?php get_template_part( 'filename_foo' ); ?>\n <?php get_template_part( 'filename_bar' ); ?>\n</div>\n</code></pre>\n\n<p>Add <code>filename_foo</code> and <code>filename_bar</code> to your theme. <code>filename_foo</code> outputs one editor-section and <code>filename_bar</code> outputs the other.</p>\n\n<p>There are many ways to add additional custom input to the admin-side of anything in WordPress which I won't discuss here.</p>\n"
},
{
"answer_id": 289835,
"author": "Cedon",
"author_id": 80069,
"author_profile": "https://wordpress.stackexchange.com/users/80069",
"pm_score": 0,
"selected": false,
"text": "<p>The way I would approach this is to use template parts and call them up based on the value of the meta field. For example:</p>\n\n<pre><code><?php\n // Standard Template Statements\n\n $template_part = // Get Custom Meta Value\n get_template_part( 'template-parts/content-split', $template_part );\n\n?>\n</code></pre>\n\n<p>So say the meta value is \"blue\", then WordPress will look for <code>{theme}/template-parts/content-split-blue.php</code> and include it there.</p>\n\n<p>You may want to set it up as a series of <code>if/then/elseif</code> checks though so there is a fallback template part to use instead.</p>\n"
}
]
| 2017/12/30 | [
"https://wordpress.stackexchange.com/questions/289812",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/58726/"
]
| I've never thought to do this with WordPress until now, but I was wondering is it possible for two templates to be chosen to create a post or page in WordPress?
When you are on the 'Edit Page' there is the 'Page Attributes>Template' section. When a custom template is chosen that will generate the main layout of the page which includes the region for an `iframe`. The `iframe` comes into play when the `custom-field` below the content editor is filled out, which would automatically call the second custom template when the page is published.
So basically, for the sake of a visual, imagine a comparison site with side-by-side view of two pages. Only now think of that example as a side-by-side view of data inputted into `the_content` (WP content editor) and `custom_field` (custom field box/field below the WP content editor).
The `iframe` is needed, but if you know what other code could be used to produce the same results would be fine. | No, you would not use two page-templates on a single page.
Yes, you can have a different admin-page layout / configuration for different page-templates.
Page-template-A could have two post-editors and page-template-B (or post-format for that matter) could have only a name, email, and featured-image.
You could use a single page template and separate includes to help organize your code.
```
<?php
// Template Name: 289812
?>
<div class="page-tpl-289812">
<?php get_template_part( 'filename_foo' ); ?>
<?php get_template_part( 'filename_bar' ); ?>
</div>
```
Add `filename_foo` and `filename_bar` to your theme. `filename_foo` outputs one editor-section and `filename_bar` outputs the other.
There are many ways to add additional custom input to the admin-side of anything in WordPress which I won't discuss here. |
289,820 | <p>****SEE Edits below****</p>
<p><strong>Edit added 1/4/2018</strong> I started over again, following the instructions. As far as I can tell everything is correct including the synchronization plugin. fpw-sync-users.php in test.oursite.com 3 occurences of $other_prefixes = array( 'wp5l_', ); fpw-sync-users.php in forum.oursite.com 3 occurrences of $other_prefixes = array( 'wp7g_', ); Is that correct? What happens when I try to log in on either site is it just refreshes the login page and nothing happens. There are no error messages </p>
<p>****END EDIT****</p>
<p>My organization is using WordPress 4.9.1.</p>
<p>What we are hoping to accomplish is having members create a user profile on secure.oursite.org and when they login, they will have access to forums.oursite.org. </p>
<p>I have not been able to find updated instructions to complete this task. Can anyone here tell me what I need to do to accomplish this, or where to get the updated instructions?</p>
<p>Thank you</p>
<p>****ADDITIONAL Information*****
I followed the instructions from @Frank P. at that link multiple times, and it is not working. I had to put everything back the way it originally was. Please see below for the steps I took and let me know if I did anything wrong. </p>
<p>The sites that I tried to test a Single Logon setup on are on subdomains: test.oursite.com and forum.oursite.com </p>
<p>test.oursite.com's database prefix is wp7g
forum.oursite.com's datebase prefix is wp5l</p>
<p>I want test.oursite.com to be where the user is created. </p>
<ol>
<li><p>I exported all the database tables from forum.oursite.com (except for wp5l_user and wp5l_usermeta) and imported them into the test.oursite.com datebase. </p></li>
<li><p>I went in to edit the wp-config.php files as instructed by Frank P. at this link <a href="https://wordpress.stackexchange.com/questions/272122/single-sign-on-between-two-wordpress-website">Single sign on between two wordpress website</a>
He says both wp-config.php files must be identical, except for the prefixes at $table_prefix, which should show the original prefix of their database. Since I want the login to be created in test.oursite.com, I copied the entire wp-config.php file to forum.oursite.com's root.</p></li>
<li><p>I went in to edit forum.oursite.com's wp-config.php file and changed the $table_prefix to wp5l then saved it. </p></li>
<li><p>I went to edit wp-config.php for test.oursite.com and added the below defines and saved it.</p>
<p>define('COOKIE_DOMAIN', '.test.oursite.com'); //this is where I think the problem might be define('COOKIEPATH', '/'); define('COOKIEHASH', md5('test.oursite.com')); define('CUSTOM_USER_TABLE', 'wp7g_users'); define('CUSTOM_USER_META_TABLE', 'wp7g_usermeta');</p></li>
<li><p>I copied and pasted those same defines to wp-config.php in forum.oursite.com and saved it.</p></li>
<li><p>I created the mu-plugins folder in wp-content for both test.oursite.com and forum.oursite.org</p></li>
</ol>
<p>7 I created fpw-sync-users.php in the mu-plugins folder for test.oursite.com and copied Frank P's code, then changed the 3 areas to my prefix and saved it as you see below.</p>
<pre><code>$other_prefixes = array(
'wp7g_',
);
</code></pre>
<ol start="8">
<li>I created fpw-sync-users.php in the mu-plugins folder for forums.oursite.com and copied the same code from the test.oursite.com mu-plugins folder so that the prefix is wp7g as Frank said it should be. I saved it. </li>
</ol>
<p>That was apparently the last step. I went to test.oursite.com and logged in, then went to forum.oursite.com and saw that I was not logged in there. I went to wp-login.php and tried to login with the same credentials from test.oursite.com. It did not accept those credentials. I tried to log in with the original admin credentials and it would not accept those either. So I tried again to make these custom configurations work several more times, trying different things in case I misunderstood something. Nothing is working. I am hoping someone can look over the steps I have taken and tell me what I am missing. </p>
<p>Thank you.</p>
<p>******wp-config.php for test.oursite.com*****</p>
<pre><code><?php
/**
* The base configuration for WordPress
*
* The wp-config.php creation script uses this file during the
* installation. You don't have to use the web site, you can
* copy this file to "wp-config.php" and fill in the values.
*
* This file contains the following configurations:
*
* * MySQL settings
* * Secret keys
* * Database table prefix
* * ABSPATH
*
* @link https://codex.wordpress.org/Editing_wp-config.php
*
* @package WordPress
*/
// ** MySQL settings - You can get this info from your web host ** //
/** The name of the database for WordPress */
define('DB_NAME', 'oursite_test2');
/** MySQL database username */
define('DB_USER', 'oursite_test2');
/** MySQL database password */
define('DB_PASSWORD', 'hidden');
/** MySQL hostname */
define('DB_HOST', 'localhost');
/** Database Charset to use in creating database tables. */
define('DB_CHARSET', 'hidden');
/** The Database Collate type. Don't change this if in doubt. */
define('DB_COLLATE', '');
/**#@+
* Authentication Unique Keys and Salts.
*
* Change these to different unique phrases!
* You can generate these using the {@link https://api.wordpress.org/secret-key/1.1/salt/ WordPress.org secret-key service}
* You can change these at any point in time to invalidate all existing cookies. This will force all users to have to log in again.
*
* @since 2.6.0
*/
define('AUTH_KEY',hidden');
define('SECURE_AUTH_KEY', 'hidden');
define('LOGGED_IN_KEY', 'hidden');
define('NONCE_KEY', 'hidden');
define('AUTH_SALT', 'hidden');
define('SECURE_AUTH_SALT', 'hidden');
define('LOGGED_IN_SALT', 'hidden');
define('NONCE_SALT', 'hidden');
define('COOKIE_DOMAIN', '.test.oursite.com');
define('COOKIEPATH', '/');
define('COOKIEHASH', md5('test.oursite.com'));
define('CUSTOM_USER_TABLE', 'wp7g_users');
define('CUSTOM_USER_META_TABLE', 'wp7g_usermeta');
/**#@-*/
/**
* WordPress Database Table prefix.
*
* You can have multiple installations in one database if you give each
* a unique prefix. Only numbers, letters, and underscores please!
*/
$table_prefix = 'wp7g_';
/**
* For developers: WordPress debugging mode.
*
* Change this to true to enable the display of notices during development.
* It is strongly recommended that plugin and theme developers use WP_DEBUG
* in their development environments.
*
* For information on other constants that can be used for debugging,
* visit the Codex.
*
* @link https://codex.wordpress.org/Debugging_in_WordPress
*/
define('WP_DEBUG', false);
/* That's all, stop editing! Happy blogging. */
/** Absolute path to the WordPress directory. */
if ( !defined('ABSPATH') )
define('ABSPATH', dirname(__FILE__) . '/');
/** Sets up WordPress vars and included files. */
require_once(ABSPATH . 'wp-settings.php');
****wp-config.php for forum.oursite.com*****
<?php
/**
* The base configuration for WordPress
*
* The wp-config.php creation script uses this file during the
* installation. You don't have to use the web site, you can
* copy this file to "wp-config.php" and fill in the values.
*
* This file contains the following configurations:
*
* * MySQL settings
* * Secret keys
* * Database table prefix
* * ABSPATH
*
* @link https://codex.wordpress.org/Editing_wp-config.php
*
* @package WordPress
*/
// ** MySQL settings - You can get this info from your web host ** //
/** The name of the database for WordPress */
define('DB_NAME', 'oursite_test2');
/** MySQL database username */
define('DB_USER', 'oursite_test2');
/** MySQL database password */
define('DB_PASSWORD', 'hidden');
/** MySQL hostname */
define('DB_HOST', 'localhost');
/** Database Charset to use in creating database tables. */
define('DB_CHARSET', 'hidden');
/** The Database Collate type. Don't change this if in doubt. */
define('DB_COLLATE', '');
/**#@+
* Authentication Unique Keys and Salts.
*
* Change these to different unique phrases!
* You can generate these using the {@link https://api.wordpress.org/secret-key/1.1/salt/ WordPress.org secret-key service}
* You can change these at any point in time to invalidate all existing cookies. This will force all users to have to log in again.
*
* @since 2.6.0
*/
define('AUTH_KEY',hidden');
define('SECURE_AUTH_KEY', 'hidden');
define('LOGGED_IN_KEY', 'hidden');
define('NONCE_KEY', 'hidden');
define('AUTH_SALT', 'hidden');
define('SECURE_AUTH_SALT', 'hidden');
define('LOGGED_IN_SALT', 'hidden');
define('NONCE_SALT', 'hidden');
define('COOKIE_DOMAIN', '.test.oursite.com');
define('COOKIEPATH', '/');
define('COOKIEHASH', md5('test.oursite.com'));
define('CUSTOM_USER_TABLE', 'wp7g_users');
define('CUSTOM_USER_META_TABLE', 'wp7g_usermeta');
/**#@-*/
/**
* WordPress Database Table prefix.
*
* You can have multiple installations in one database if you give each
* a unique prefix. Only numbers, letters, and underscores please!
*/
$table_prefix = 'wp5l_';
/**
* For developers: WordPress debugging mode.
*
* Change this to true to enable the display of notices during development.
* It is strongly recommended that plugin and theme developers use WP_DEBUG
* in their development environments.
*
* For information on other constants that can be used for debugging,
* visit the Codex.
*
* @link https://codex.wordpress.org/Debugging_in_WordPress
*/
define('WP_DEBUG', false);
/* That's all, stop editing! Happy blogging. */
/** Absolute path to the WordPress directory. */
if ( !defined('ABSPATH') )
define('ABSPATH', dirname(__FILE__) . '/');
/** Sets up WordPress vars and included files. */
require_once(ABSPATH . 'wp-settings.php');
</code></pre>
| [
{
"answer_id": 289850,
"author": "Frank P. Walentynowicz",
"author_id": 32851,
"author_profile": "https://wordpress.stackexchange.com/users/32851",
"pm_score": 1,
"selected": false,
"text": "<p>In both <code>wp-config.php</code> files, change the following defines:</p>\n\n<pre><code>define('COOKIE_DOMAIN', '.test.oursite.com');\ndefine('COOKIEHASH', md5('test.oursite.com'));\n</code></pre>\n\n<p>to:</p>\n\n<pre><code>define('COOKIE_DOMAIN', '.oursite.com');\ndefine('COOKIEHASH', md5('oursite.com'));\n</code></pre>\n\n<p>Go to <code>test.oursite.com/wp-admin/</code> and login as an administrator. Go to <code>Users -> Your Profile</code> and click on <code>Update Profile</code> button. Now go to <code>forums.oursite.com/wp-admin/</code>. You should be logged in there. If synchronization plugins in <code>mu-plugins</code> for both sites are correct, all is done. If they are incorrect, you'll get a message, that you don't have privileges to access this page. In that case, you'll have to correct synchronization plugins, according to my original answer. If you see login form, your <code>wp-config.php</code> files are not set correctly. </p>\n"
},
{
"answer_id": 360810,
"author": "froger.me",
"author_id": 130448,
"author_profile": "https://wordpress.stackexchange.com/users/130448",
"pm_score": 0,
"selected": false,
"text": "<p>If you want to keep the websites completely separated, you can with <a href=\"https://wordpress.org/plugins/wp-remote-users-sync/advanced/\" rel=\"nofollow noreferrer\">WP Remote Users Sync</a> (disclaimer: I am the author of the plugin)</p>\n"
}
]
| 2017/12/31 | [
"https://wordpress.stackexchange.com/questions/289820",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/134043/"
]
| \*\*\*\*SEE Edits below\*\*\*\*
**Edit added 1/4/2018** I started over again, following the instructions. As far as I can tell everything is correct including the synchronization plugin. fpw-sync-users.php in test.oursite.com 3 occurences of $other\_prefixes = array( 'wp5l\_', ); fpw-sync-users.php in forum.oursite.com 3 occurrences of $other\_prefixes = array( 'wp7g\_', ); Is that correct? What happens when I try to log in on either site is it just refreshes the login page and nothing happens. There are no error messages
\*\*\*\*END EDIT\*\*\*\*
My organization is using WordPress 4.9.1.
What we are hoping to accomplish is having members create a user profile on secure.oursite.org and when they login, they will have access to forums.oursite.org.
I have not been able to find updated instructions to complete this task. Can anyone here tell me what I need to do to accomplish this, or where to get the updated instructions?
Thank you
\*\*\*\*ADDITIONAL Information\*\*\*\*\*
I followed the instructions from @Frank P. at that link multiple times, and it is not working. I had to put everything back the way it originally was. Please see below for the steps I took and let me know if I did anything wrong.
The sites that I tried to test a Single Logon setup on are on subdomains: test.oursite.com and forum.oursite.com
test.oursite.com's database prefix is wp7g
forum.oursite.com's datebase prefix is wp5l
I want test.oursite.com to be where the user is created.
1. I exported all the database tables from forum.oursite.com (except for wp5l\_user and wp5l\_usermeta) and imported them into the test.oursite.com datebase.
2. I went in to edit the wp-config.php files as instructed by Frank P. at this link [Single sign on between two wordpress website](https://wordpress.stackexchange.com/questions/272122/single-sign-on-between-two-wordpress-website)
He says both wp-config.php files must be identical, except for the prefixes at $table\_prefix, which should show the original prefix of their database. Since I want the login to be created in test.oursite.com, I copied the entire wp-config.php file to forum.oursite.com's root.
3. I went in to edit forum.oursite.com's wp-config.php file and changed the $table\_prefix to wp5l then saved it.
4. I went to edit wp-config.php for test.oursite.com and added the below defines and saved it.
define('COOKIE\_DOMAIN', '.test.oursite.com'); //this is where I think the problem might be define('COOKIEPATH', '/'); define('COOKIEHASH', md5('test.oursite.com')); define('CUSTOM\_USER\_TABLE', 'wp7g\_users'); define('CUSTOM\_USER\_META\_TABLE', 'wp7g\_usermeta');
5. I copied and pasted those same defines to wp-config.php in forum.oursite.com and saved it.
6. I created the mu-plugins folder in wp-content for both test.oursite.com and forum.oursite.org
7 I created fpw-sync-users.php in the mu-plugins folder for test.oursite.com and copied Frank P's code, then changed the 3 areas to my prefix and saved it as you see below.
```
$other_prefixes = array(
'wp7g_',
);
```
8. I created fpw-sync-users.php in the mu-plugins folder for forums.oursite.com and copied the same code from the test.oursite.com mu-plugins folder so that the prefix is wp7g as Frank said it should be. I saved it.
That was apparently the last step. I went to test.oursite.com and logged in, then went to forum.oursite.com and saw that I was not logged in there. I went to wp-login.php and tried to login with the same credentials from test.oursite.com. It did not accept those credentials. I tried to log in with the original admin credentials and it would not accept those either. So I tried again to make these custom configurations work several more times, trying different things in case I misunderstood something. Nothing is working. I am hoping someone can look over the steps I have taken and tell me what I am missing.
Thank you.
\*\*\*\*\*\*wp-config.php for test.oursite.com\*\*\*\*\*
```
<?php
/**
* The base configuration for WordPress
*
* The wp-config.php creation script uses this file during the
* installation. You don't have to use the web site, you can
* copy this file to "wp-config.php" and fill in the values.
*
* This file contains the following configurations:
*
* * MySQL settings
* * Secret keys
* * Database table prefix
* * ABSPATH
*
* @link https://codex.wordpress.org/Editing_wp-config.php
*
* @package WordPress
*/
// ** MySQL settings - You can get this info from your web host ** //
/** The name of the database for WordPress */
define('DB_NAME', 'oursite_test2');
/** MySQL database username */
define('DB_USER', 'oursite_test2');
/** MySQL database password */
define('DB_PASSWORD', 'hidden');
/** MySQL hostname */
define('DB_HOST', 'localhost');
/** Database Charset to use in creating database tables. */
define('DB_CHARSET', 'hidden');
/** The Database Collate type. Don't change this if in doubt. */
define('DB_COLLATE', '');
/**#@+
* Authentication Unique Keys and Salts.
*
* Change these to different unique phrases!
* You can generate these using the {@link https://api.wordpress.org/secret-key/1.1/salt/ WordPress.org secret-key service}
* You can change these at any point in time to invalidate all existing cookies. This will force all users to have to log in again.
*
* @since 2.6.0
*/
define('AUTH_KEY',hidden');
define('SECURE_AUTH_KEY', 'hidden');
define('LOGGED_IN_KEY', 'hidden');
define('NONCE_KEY', 'hidden');
define('AUTH_SALT', 'hidden');
define('SECURE_AUTH_SALT', 'hidden');
define('LOGGED_IN_SALT', 'hidden');
define('NONCE_SALT', 'hidden');
define('COOKIE_DOMAIN', '.test.oursite.com');
define('COOKIEPATH', '/');
define('COOKIEHASH', md5('test.oursite.com'));
define('CUSTOM_USER_TABLE', 'wp7g_users');
define('CUSTOM_USER_META_TABLE', 'wp7g_usermeta');
/**#@-*/
/**
* WordPress Database Table prefix.
*
* You can have multiple installations in one database if you give each
* a unique prefix. Only numbers, letters, and underscores please!
*/
$table_prefix = 'wp7g_';
/**
* For developers: WordPress debugging mode.
*
* Change this to true to enable the display of notices during development.
* It is strongly recommended that plugin and theme developers use WP_DEBUG
* in their development environments.
*
* For information on other constants that can be used for debugging,
* visit the Codex.
*
* @link https://codex.wordpress.org/Debugging_in_WordPress
*/
define('WP_DEBUG', false);
/* That's all, stop editing! Happy blogging. */
/** Absolute path to the WordPress directory. */
if ( !defined('ABSPATH') )
define('ABSPATH', dirname(__FILE__) . '/');
/** Sets up WordPress vars and included files. */
require_once(ABSPATH . 'wp-settings.php');
****wp-config.php for forum.oursite.com*****
<?php
/**
* The base configuration for WordPress
*
* The wp-config.php creation script uses this file during the
* installation. You don't have to use the web site, you can
* copy this file to "wp-config.php" and fill in the values.
*
* This file contains the following configurations:
*
* * MySQL settings
* * Secret keys
* * Database table prefix
* * ABSPATH
*
* @link https://codex.wordpress.org/Editing_wp-config.php
*
* @package WordPress
*/
// ** MySQL settings - You can get this info from your web host ** //
/** The name of the database for WordPress */
define('DB_NAME', 'oursite_test2');
/** MySQL database username */
define('DB_USER', 'oursite_test2');
/** MySQL database password */
define('DB_PASSWORD', 'hidden');
/** MySQL hostname */
define('DB_HOST', 'localhost');
/** Database Charset to use in creating database tables. */
define('DB_CHARSET', 'hidden');
/** The Database Collate type. Don't change this if in doubt. */
define('DB_COLLATE', '');
/**#@+
* Authentication Unique Keys and Salts.
*
* Change these to different unique phrases!
* You can generate these using the {@link https://api.wordpress.org/secret-key/1.1/salt/ WordPress.org secret-key service}
* You can change these at any point in time to invalidate all existing cookies. This will force all users to have to log in again.
*
* @since 2.6.0
*/
define('AUTH_KEY',hidden');
define('SECURE_AUTH_KEY', 'hidden');
define('LOGGED_IN_KEY', 'hidden');
define('NONCE_KEY', 'hidden');
define('AUTH_SALT', 'hidden');
define('SECURE_AUTH_SALT', 'hidden');
define('LOGGED_IN_SALT', 'hidden');
define('NONCE_SALT', 'hidden');
define('COOKIE_DOMAIN', '.test.oursite.com');
define('COOKIEPATH', '/');
define('COOKIEHASH', md5('test.oursite.com'));
define('CUSTOM_USER_TABLE', 'wp7g_users');
define('CUSTOM_USER_META_TABLE', 'wp7g_usermeta');
/**#@-*/
/**
* WordPress Database Table prefix.
*
* You can have multiple installations in one database if you give each
* a unique prefix. Only numbers, letters, and underscores please!
*/
$table_prefix = 'wp5l_';
/**
* For developers: WordPress debugging mode.
*
* Change this to true to enable the display of notices during development.
* It is strongly recommended that plugin and theme developers use WP_DEBUG
* in their development environments.
*
* For information on other constants that can be used for debugging,
* visit the Codex.
*
* @link https://codex.wordpress.org/Debugging_in_WordPress
*/
define('WP_DEBUG', false);
/* That's all, stop editing! Happy blogging. */
/** Absolute path to the WordPress directory. */
if ( !defined('ABSPATH') )
define('ABSPATH', dirname(__FILE__) . '/');
/** Sets up WordPress vars and included files. */
require_once(ABSPATH . 'wp-settings.php');
``` | In both `wp-config.php` files, change the following defines:
```
define('COOKIE_DOMAIN', '.test.oursite.com');
define('COOKIEHASH', md5('test.oursite.com'));
```
to:
```
define('COOKIE_DOMAIN', '.oursite.com');
define('COOKIEHASH', md5('oursite.com'));
```
Go to `test.oursite.com/wp-admin/` and login as an administrator. Go to `Users -> Your Profile` and click on `Update Profile` button. Now go to `forums.oursite.com/wp-admin/`. You should be logged in there. If synchronization plugins in `mu-plugins` for both sites are correct, all is done. If they are incorrect, you'll get a message, that you don't have privileges to access this page. In that case, you'll have to correct synchronization plugins, according to my original answer. If you see login form, your `wp-config.php` files are not set correctly. |
289,836 | <p>i have created a meta box oembed with clone:</p>
<pre><code>function media( $meta_boxes ) {
$prefix = '';
$meta_boxes[] = array(
'id' => 'media_1',
'title' => esc_html__( 'Media', 'media' ),
'post_types' => array( 'post','personal_projects' ),
'context' => 'advanced',
'priority' => 'high',
'autosave' => true,
'fields' => array(
array(
'id' => $prefix . 'image_advanced_2',
'type' => 'image_advanced',
'name' => esc_html__( 'Gallery', 'media' ),
),
array(
'id' => $prefix . 'video_1',
'type' => 'video',
'name' => esc_html__( 'Video', 'media' ),
),
array(
'id' => $prefix . 'oembed_1',
'type'=> 'oembed',
'name' => esc_html__( 'Embed Video', 'media' ),
'clone' => true,
'add_button' => esc_html__( 'Add video', 'media' ),
'sort_clone' => true,
),
array(
'id' => $prefix . 'url_1',
'type' => 'url',
'name' => esc_html__( 'URL', 'media' ),
'clone' => true,
),
),
);
return $meta_boxes;
}
add_filter( 'rwmb_meta_boxes', 'media' );
</code></pre>
<p>it works very good except i can not get the videos with foreach</p>
<p>i have a vimeo and a youtube video.</p>
<pre><code>$btsvideoembeds = array();
$btsvideoembeds = rwmb_meta ( 'oembed_1', array( 'type' => 'oembed' ) );
foreach ( $btsvideoembeds as $btsvideoembed ) {
echo '<div>';
echo $btsvideoembed;
echo '</div>';
}
</code></pre>
<p>it return string not array</p>
| [
{
"answer_id": 289837,
"author": "Phaidonas Gialis",
"author_id": 119240,
"author_profile": "https://wordpress.stackexchange.com/users/119240",
"pm_score": 1,
"selected": false,
"text": "<p>i changed the code like this, and now works:</p>\n\n<pre><code>$btsvideoembeds = array();\n$btsvideoembeds = rwmb_get_value( 'oembed_1', array( 'type' => 'oembed' ) );\n\n\n foreach ( $btsvideoembeds as $btsvideoembed ) {\n echo '<div>';\n echo wp_oembed_get( $btsvideoembed);\n echo '</div>';\n }\n</code></pre>\n"
},
{
"answer_id": 289844,
"author": "Dev",
"author_id": 104464,
"author_profile": "https://wordpress.stackexchange.com/users/104464",
"pm_score": 1,
"selected": true,
"text": "<p>You could also code it like this :</p>\n\n<pre><code>$btsvideoembeds = rwmb_get_value( 'oembed_1', array( 'type' => 'oembed' ) );\n\nforeach ( (array) $btsvideoembeds as $btsvideoembed ) {\n\nprintf('%s', wp_oembed_get( $btsvideoembed ) );\n</code></pre>\n"
}
]
| 2017/12/31 | [
"https://wordpress.stackexchange.com/questions/289836",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/119240/"
]
| i have created a meta box oembed with clone:
```
function media( $meta_boxes ) {
$prefix = '';
$meta_boxes[] = array(
'id' => 'media_1',
'title' => esc_html__( 'Media', 'media' ),
'post_types' => array( 'post','personal_projects' ),
'context' => 'advanced',
'priority' => 'high',
'autosave' => true,
'fields' => array(
array(
'id' => $prefix . 'image_advanced_2',
'type' => 'image_advanced',
'name' => esc_html__( 'Gallery', 'media' ),
),
array(
'id' => $prefix . 'video_1',
'type' => 'video',
'name' => esc_html__( 'Video', 'media' ),
),
array(
'id' => $prefix . 'oembed_1',
'type'=> 'oembed',
'name' => esc_html__( 'Embed Video', 'media' ),
'clone' => true,
'add_button' => esc_html__( 'Add video', 'media' ),
'sort_clone' => true,
),
array(
'id' => $prefix . 'url_1',
'type' => 'url',
'name' => esc_html__( 'URL', 'media' ),
'clone' => true,
),
),
);
return $meta_boxes;
}
add_filter( 'rwmb_meta_boxes', 'media' );
```
it works very good except i can not get the videos with foreach
i have a vimeo and a youtube video.
```
$btsvideoembeds = array();
$btsvideoembeds = rwmb_meta ( 'oembed_1', array( 'type' => 'oembed' ) );
foreach ( $btsvideoembeds as $btsvideoembed ) {
echo '<div>';
echo $btsvideoembed;
echo '</div>';
}
```
it return string not array | You could also code it like this :
```
$btsvideoembeds = rwmb_get_value( 'oembed_1', array( 'type' => 'oembed' ) );
foreach ( (array) $btsvideoembeds as $btsvideoembed ) {
printf('%s', wp_oembed_get( $btsvideoembed ) );
``` |
289,868 | <p>that is my source: <a href="http://view-source:buhehe.de" rel="nofollow noreferrer">view-source:buhehe.de</a>
i am trying to deque some script form function.php
i mean these two:</p>
<pre><code><script type="text/javascript" src="http://buhehe.de/wp-content/themes/tema/js/jquery-3.2.1.min.js"></script>
<script type='text/javascript' src='http://buhehe.de/wp-includes/js/jquery/jquery.js?ver=1.12.4'></script>
</code></pre>
<p>I added following code in Function.php but it doesn't deques scripts from source:</p>
<pre><code>function dequeue_script() {
wp_dequeue_script( 'http://buhehe.de/wp-content/themes/heatt/js/small-menu.js?ver=4.9.1' );
wp_dequeue_script( 'http://buhehe.de/wp-includes/js/wp-embed.min.js?ver=4.9.1' );
wp_dequeue_script( 'http://buhehe.de/wp-includes/js/wp-embed.min.js' );
}
add_action( 'wp_print_scripts', 'dequeue_script', 100 );
</code></pre>
<p>How can i deque these scripts fcrom source?</p>
| [
{
"answer_id": 290029,
"author": "bueltge",
"author_id": 170,
"author_profile": "https://wordpress.stackexchange.com/users/170",
"pm_score": 2,
"selected": false,
"text": "<p>I think is not an problem in your WP installation. The site works as encoding UTF-8, also your feed etc. </p>\n\n<h3>Validating</h3>\n\n<p>For an validating of strings should use the PHP function <a href=\"http://php.net/manual/de/function.mb-check-encoding.php\" rel=\"nofollow noreferrer\"><code>mb_check_encoding</code></a>. A small script should check your database tables, the content so that you have feedback about your data inside the database tables.</p>\n\n<p>Also it the libraray <a href=\"https://github.com/tchwork/utf8\" rel=\"nofollow noreferrer\">tchwork-grekas/utf8</a> helpful, for finding problems also fix the wrong strings.</p>\n\n<h3>Fix them via custom script</h3>\n\n<p>However if you will only search in your database, search via a plugin for an strings should helps you. Alternative is an custom script, that check and fix them. I think the <a href=\"https://github.com/neitanod/forceutf8\" rel=\"nofollow noreferrer\">forceutf8</a> library is helpful. The method <code>fixUTF8</code> fix your problems, if you have inside your data.</p>\n\n<p>Alternative is also the library <em>Patchwork-UTF8</em> in the first abstract, see above.</p>\n\n<h3>mySQL Table Collation</h3>\n\n<p>Before you should check the Collation of all tables. You check their encoding by looking at the Collation value in the output of <a href=\"https://dev.mysql.com/doc/refman/5.5/en/show-table-status.html\" rel=\"nofollow noreferrer\"><code>SHOW TABLE STATUS</code></a> (in phpMyAdmin or Adminer this is shown in the list of tables).</p>\n\n<pre><code>SHOW TABLE STATUS FROM <YOUR_DATABASE>\n</code></pre>\n\n<h3>mySQL Variable</h3>\n\n<p>You can also check each variable, run the follow mysql command in your database to verify that everything has properly been set to use the UTF-8 encoding.</p>\n\n<pre><code>SHOW VARIABLES LIKE 'char%';\n</code></pre>\n\n<h3>Convert</h3>\n\n<p>Convert the table to InnoDB and utf8mb4, the <code>posts</code> table</p>\n\n<pre><code>ALTER TABLE wp_posts ENGINE=InnoDB ROW_FORMAT=DYNAMIC;\nALTER TABLE wp_posts CONVERT TO CHARACTER SET utf8mb4 COLLATE utf8mb4_unicode_ci;\n</code></pre>\n\n<h3>WP Config</h3>\n\n<p>Check the <code>wp-config.php</code>\n<code>utf8mb4</code> is your choice since WordPress 4.2, full UTF-8 support.</p>\n\n<pre><code>define( 'DB_CHARSET', 'utf8mb4' ); \n</code></pre>\n\n<h3>Links</h3>\n\n<ul>\n<li><a href=\"https://www.toptal.com/php/a-utf-8-primer-for-php-and-mysql\" rel=\"nofollow noreferrer\">Helpful post</a> about switch from a NonUTF-8 database to UTF-8 for more details in the deep.</li>\n<li><a href=\"https://tympanus.net/codrops/2009/08/31/solving-php-mysql-utf-8-issues/\" rel=\"nofollow noreferrer\">Solving PHP MySQL UTF-8 issues</a> </li>\n</ul>\n"
},
{
"answer_id": 290436,
"author": "SagiLow",
"author_id": 134064,
"author_profile": "https://wordpress.stackexchange.com/users/134064",
"pm_score": 1,
"selected": true,
"text": "<p>I've found the issue.<br>\nUTF8 might produce a multibyte string (when using Hebrew characters for example).<br>\nFacebook truncates this string a post is shared to keep the description under max number of characters.<br>\nHowever, they might truncate a multibyte character in the middle which will result in UTF8 invalid character: οΏ½<br>\nThis issue actually reproduces in all multibyte websites.<br>\nThe only workaround I've found is limiting the <code>og:description</code> to Facebook's max number of characters (about 110 in comment and 300 in post) \nI've submitted a bug to Facebook OpenGraph platform and I hope it will be fixed shortly.</p>\n"
}
]
| 2018/01/01 | [
"https://wordpress.stackexchange.com/questions/289868",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/133900/"
]
| that is my source: [view-source:buhehe.de](http://view-source:buhehe.de)
i am trying to deque some script form function.php
i mean these two:
```
<script type="text/javascript" src="http://buhehe.de/wp-content/themes/tema/js/jquery-3.2.1.min.js"></script>
<script type='text/javascript' src='http://buhehe.de/wp-includes/js/jquery/jquery.js?ver=1.12.4'></script>
```
I added following code in Function.php but it doesn't deques scripts from source:
```
function dequeue_script() {
wp_dequeue_script( 'http://buhehe.de/wp-content/themes/heatt/js/small-menu.js?ver=4.9.1' );
wp_dequeue_script( 'http://buhehe.de/wp-includes/js/wp-embed.min.js?ver=4.9.1' );
wp_dequeue_script( 'http://buhehe.de/wp-includes/js/wp-embed.min.js' );
}
add_action( 'wp_print_scripts', 'dequeue_script', 100 );
```
How can i deque these scripts fcrom source? | I've found the issue.
UTF8 might produce a multibyte string (when using Hebrew characters for example).
Facebook truncates this string a post is shared to keep the description under max number of characters.
However, they might truncate a multibyte character in the middle which will result in UTF8 invalid character: οΏ½
This issue actually reproduces in all multibyte websites.
The only workaround I've found is limiting the `og:description` to Facebook's max number of characters (about 110 in comment and 300 in post)
I've submitted a bug to Facebook OpenGraph platform and I hope it will be fixed shortly. |
289,869 | <p>well i can access the sites: </p>
<pre><code>www.foo.com and
www.bar.com
</code></pre>
<p>but i cannot access the login - the sites are blank.</p>
<pre><code>foo.com/wp-login.php
bar.com/wp-login.php
</code></pre>
<p>i have the following logs.</p>
<pre><code>[Mon Jan 01 16:26:03.229924 2018] [core:notice] [pid 17589] AH00052: child pid 24869 exit signal Segmentation fault (11)
[Mon Jan 01 16:39:54.242584 2018] [core:notice] [pid 17589] AH00052: child pid 24872 exit signal Segmentation fault (11)
[Mon Jan 01 16:39:56.245833 2018] [core:notice] [pid 17589] AH00052: child pid 24870 exit signal Segmentation fault (11)
[Mon Jan 01 16:39:56.245959 2018] [core:notice] [pid 17589] AH00052: child pid 24871 exit signal Segmentation fault (11)
[Mon Jan 01 16:39:56.246014 2018] [core:notice] [pid 17589] AH00052: child pid 24873 exit signal Segmentation fault (11)
[Mon Jan 01 16:49:06.968278 2018] [core:notice] [pid 17589] AH00052: child pid 25032 exit signal Segmentation fault (11)
[Mon Jan 01 16:53:03.287697 2018] [core:notice] [pid 17589] AH00052: child pid 25034 exit signal Segmentation fault (11)
[Mon Jan 01 16:53:07.293645 2018] [core:notice] [pid 17589] AH00052: child pid 25039 exit signal Segmentation fault (11)
[Mon Jan 01 16:53:59.364044 2018] [core:notice] [pid 17589] AH00052: child pid 25106 exit signal Segmentation fault (11)
</code></pre>
<p>in other words - the admin-area is not acessible</p>
<p>what can i do: should i change the wp-login.php url to /login/
to get it to work: so all links in registration and forgot password emails have /login/ rather than wp-login.php.</p>
| [
{
"answer_id": 289870,
"author": "Rick Hellewell",
"author_id": 29416,
"author_profile": "https://wordpress.stackexchange.com/users/29416",
"pm_score": 1,
"selected": false,
"text": "<p>You probably have a problem-causing plugin. </p>\n\n<p>Look at the error.log file which will tell you the file that is causing the problem. Rename that plugin's folder (use your hosting control panel's File Manager) and retry. That should get you into the admin area. Then you can contact the plugin's support forum to figure out the fix - or just delete the plugin.</p>\n\n<p>Alternately, you can rename the entire plugin folder (in wp-content) so that all plugins are disabled, then move those plugin files individually by their folders to re-enable them.</p>\n\n<p>But looking at the error.log file (via your hosting cPanel or via FTP program or hosting File Manager) will help you zero in on the problem.</p>\n"
},
{
"answer_id": 289961,
"author": "dibert",
"author_id": 134169,
"author_profile": "https://wordpress.stackexchange.com/users/134169",
"pm_score": -1,
"selected": false,
"text": "<p>@the admins: this is dilbert speaking i just have logged in. </p>\n\n<p>@rick and all the others: many many thanks for all you hints. \nvery interesting: all runs in vhost on a root-server.</p>\n\n<p>i have the issues on three sites on the server:</p>\n\n<p>i activated an older site - which was closed - running WordPress 4.7.8 - with the theme: \"Twenty Seventeen theme\"\nwith this all works nice - and i can access the login. </p>\n\n<p>For miskate i change the url of my wordpress on settings -> general. \nIn order to get more infos about what is happening i need to see the php-error-logs</p>\n\n<p>to see this i have to change the wp-config.php file and add this too config.php</p>\n\n<pre><code>define('WP_HOME','localhost/wordpress');\ndefine('WP_SITEURL','localhost/wordpress');\n</code></pre>\n\n<p>Then i need to restart the apache and i hope i could enter again on my admin panel. ..But everytime i u use the .../wordpress/wp-login.php i receive a 404 not found</p>\n\n<p>BTW: SEE THE SESSION </p>\n\n<pre><code>Session Support enabled\nRegistered save handlers files user mm\nRegistered serializer handlers php_serialize php php_binary\nDirective Local Value Master Value\nsession.auto_start Off Off\nsession.cache_expire 180 180\nsession.cache_limiter nocache nocache\nsession.cookie_domain no value no value\nsession.cookie_httponly Off Off\nsession.cookie_lifetime 3600 3600\nsession.cookie_path / /\nsession.cookie_secure Off Off\nsession.entropy_file /dev/urandom /dev/urandom\nsession.entropy_length 32 32\nsession.gc_divisor 1000 1000\nsession.gc_maxlifetime 3600 3600\nsession.gc_probability 1 1\nsession.hash_bits_per_character 5 5\nsession.hash_function 0 0\nsession.name PHPSESSID PHPSESSID\nsession.referer_check no value no value\nsession.save_handler mm mm\nsession.save_path no value no value\nsession.serialize_handler php php\nsession.upload_progress.cleanup On On\nsession.upload_progress.enabled On On\nsession.upload_progress.freq 1% 1%\nsession.upload_progress.min_freq 1 1\nsession.upload_progress.name PHP_SESSION_UPLOAD_PROGRESS PHP_SESSION_UPLOAD_PROGRESS\nsession.upload_progress.prefix upload_progress_ upload_progress_\nsession.use_cookies On On\nsession.use_only_cookies On On\nsession.use_strict_mode Off Off\nsession.use_trans_sid 0 0\n</code></pre>\n"
}
]
| 2018/01/01 | [
"https://wordpress.stackexchange.com/questions/289869",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/130711/"
]
| well i can access the sites:
```
www.foo.com and
www.bar.com
```
but i cannot access the login - the sites are blank.
```
foo.com/wp-login.php
bar.com/wp-login.php
```
i have the following logs.
```
[Mon Jan 01 16:26:03.229924 2018] [core:notice] [pid 17589] AH00052: child pid 24869 exit signal Segmentation fault (11)
[Mon Jan 01 16:39:54.242584 2018] [core:notice] [pid 17589] AH00052: child pid 24872 exit signal Segmentation fault (11)
[Mon Jan 01 16:39:56.245833 2018] [core:notice] [pid 17589] AH00052: child pid 24870 exit signal Segmentation fault (11)
[Mon Jan 01 16:39:56.245959 2018] [core:notice] [pid 17589] AH00052: child pid 24871 exit signal Segmentation fault (11)
[Mon Jan 01 16:39:56.246014 2018] [core:notice] [pid 17589] AH00052: child pid 24873 exit signal Segmentation fault (11)
[Mon Jan 01 16:49:06.968278 2018] [core:notice] [pid 17589] AH00052: child pid 25032 exit signal Segmentation fault (11)
[Mon Jan 01 16:53:03.287697 2018] [core:notice] [pid 17589] AH00052: child pid 25034 exit signal Segmentation fault (11)
[Mon Jan 01 16:53:07.293645 2018] [core:notice] [pid 17589] AH00052: child pid 25039 exit signal Segmentation fault (11)
[Mon Jan 01 16:53:59.364044 2018] [core:notice] [pid 17589] AH00052: child pid 25106 exit signal Segmentation fault (11)
```
in other words - the admin-area is not acessible
what can i do: should i change the wp-login.php url to /login/
to get it to work: so all links in registration and forgot password emails have /login/ rather than wp-login.php. | You probably have a problem-causing plugin.
Look at the error.log file which will tell you the file that is causing the problem. Rename that plugin's folder (use your hosting control panel's File Manager) and retry. That should get you into the admin area. Then you can contact the plugin's support forum to figure out the fix - or just delete the plugin.
Alternately, you can rename the entire plugin folder (in wp-content) so that all plugins are disabled, then move those plugin files individually by their folders to re-enable them.
But looking at the error.log file (via your hosting cPanel or via FTP program or hosting File Manager) will help you zero in on the problem. |
289,892 | <p>I have made wp_query like below. This is some part of them. And it works.</p>
<pre><code>$args = .....;
$query = new WP_Query($args);
while($query->have_posts() ) :
$query->the_post();
?>
<div class="each">
<h4><?php the_title(); ?> </h4>
</div>
<?php endwhile; wp_reset_query(); ?>
</code></pre>
<p>This shows like this.</p>
<pre><code><div>title 1</div>
<div>title 2</div>
<div>title 3</div>
...
</code></pre>
<p>At this point, when I click one of the titles, it needs to link to the details of the clicked post. But I don''t know how to link to the detail page. I think it should be linked to 'single.php'. is this right? and how to link to that detail page(maybe singles.php)? thank you.</p>
| [
{
"answer_id": 289870,
"author": "Rick Hellewell",
"author_id": 29416,
"author_profile": "https://wordpress.stackexchange.com/users/29416",
"pm_score": 1,
"selected": false,
"text": "<p>You probably have a problem-causing plugin. </p>\n\n<p>Look at the error.log file which will tell you the file that is causing the problem. Rename that plugin's folder (use your hosting control panel's File Manager) and retry. That should get you into the admin area. Then you can contact the plugin's support forum to figure out the fix - or just delete the plugin.</p>\n\n<p>Alternately, you can rename the entire plugin folder (in wp-content) so that all plugins are disabled, then move those plugin files individually by their folders to re-enable them.</p>\n\n<p>But looking at the error.log file (via your hosting cPanel or via FTP program or hosting File Manager) will help you zero in on the problem.</p>\n"
},
{
"answer_id": 289961,
"author": "dibert",
"author_id": 134169,
"author_profile": "https://wordpress.stackexchange.com/users/134169",
"pm_score": -1,
"selected": false,
"text": "<p>@the admins: this is dilbert speaking i just have logged in. </p>\n\n<p>@rick and all the others: many many thanks for all you hints. \nvery interesting: all runs in vhost on a root-server.</p>\n\n<p>i have the issues on three sites on the server:</p>\n\n<p>i activated an older site - which was closed - running WordPress 4.7.8 - with the theme: \"Twenty Seventeen theme\"\nwith this all works nice - and i can access the login. </p>\n\n<p>For miskate i change the url of my wordpress on settings -> general. \nIn order to get more infos about what is happening i need to see the php-error-logs</p>\n\n<p>to see this i have to change the wp-config.php file and add this too config.php</p>\n\n<pre><code>define('WP_HOME','localhost/wordpress');\ndefine('WP_SITEURL','localhost/wordpress');\n</code></pre>\n\n<p>Then i need to restart the apache and i hope i could enter again on my admin panel. ..But everytime i u use the .../wordpress/wp-login.php i receive a 404 not found</p>\n\n<p>BTW: SEE THE SESSION </p>\n\n<pre><code>Session Support enabled\nRegistered save handlers files user mm\nRegistered serializer handlers php_serialize php php_binary\nDirective Local Value Master Value\nsession.auto_start Off Off\nsession.cache_expire 180 180\nsession.cache_limiter nocache nocache\nsession.cookie_domain no value no value\nsession.cookie_httponly Off Off\nsession.cookie_lifetime 3600 3600\nsession.cookie_path / /\nsession.cookie_secure Off Off\nsession.entropy_file /dev/urandom /dev/urandom\nsession.entropy_length 32 32\nsession.gc_divisor 1000 1000\nsession.gc_maxlifetime 3600 3600\nsession.gc_probability 1 1\nsession.hash_bits_per_character 5 5\nsession.hash_function 0 0\nsession.name PHPSESSID PHPSESSID\nsession.referer_check no value no value\nsession.save_handler mm mm\nsession.save_path no value no value\nsession.serialize_handler php php\nsession.upload_progress.cleanup On On\nsession.upload_progress.enabled On On\nsession.upload_progress.freq 1% 1%\nsession.upload_progress.min_freq 1 1\nsession.upload_progress.name PHP_SESSION_UPLOAD_PROGRESS PHP_SESSION_UPLOAD_PROGRESS\nsession.upload_progress.prefix upload_progress_ upload_progress_\nsession.use_cookies On On\nsession.use_only_cookies On On\nsession.use_strict_mode Off Off\nsession.use_trans_sid 0 0\n</code></pre>\n"
}
]
| 2018/01/02 | [
"https://wordpress.stackexchange.com/questions/289892",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/133185/"
]
| I have made wp\_query like below. This is some part of them. And it works.
```
$args = .....;
$query = new WP_Query($args);
while($query->have_posts() ) :
$query->the_post();
?>
<div class="each">
<h4><?php the_title(); ?> </h4>
</div>
<?php endwhile; wp_reset_query(); ?>
```
This shows like this.
```
<div>title 1</div>
<div>title 2</div>
<div>title 3</div>
...
```
At this point, when I click one of the titles, it needs to link to the details of the clicked post. But I don''t know how to link to the detail page. I think it should be linked to 'single.php'. is this right? and how to link to that detail page(maybe singles.php)? thank you. | You probably have a problem-causing plugin.
Look at the error.log file which will tell you the file that is causing the problem. Rename that plugin's folder (use your hosting control panel's File Manager) and retry. That should get you into the admin area. Then you can contact the plugin's support forum to figure out the fix - or just delete the plugin.
Alternately, you can rename the entire plugin folder (in wp-content) so that all plugins are disabled, then move those plugin files individually by their folders to re-enable them.
But looking at the error.log file (via your hosting cPanel or via FTP program or hosting File Manager) will help you zero in on the problem. |
289,929 | <pre><code>if ( ! function_exists( 'loadingscripts' ) ) {
function loadingscripts() {
// Register the script like this for a theme:
wp_register_script( 'custom-js', get_template_directory_uri() . '/js/custom.js', array( 'jquery' ), '1.1', true );
wp_enqueue_script( 'custom-js' );
/* Load the stylesheets. */
// wp_enqueue_style( 'fontawesome', THEMEROOT . '/inc/lib/fontawesome/css/font-awesome.min.css' );
wp_enqueue_style( 'layout', THEMEROOT . '/css/layout.css' );
wp_enqueue_style( 'styles', THEMEROOT . '/css/style.css' );
}
}
add_action('wp_enqueue_scripts','loadingscripts');
</code></pre>
<p>I think the Javascript is loading before the DOM because in its pure HTML version I was loading the javascript in the footer, but in the WordPress conversion, it doesn't work. What is the fix?</p>
| [
{
"answer_id": 289932,
"author": "Tom J Nowell",
"author_id": 736,
"author_profile": "https://wordpress.stackexchange.com/users/736",
"pm_score": 2,
"selected": true,
"text": "<p>Javascript runs as soon as it's loaded, you need to wait for the DOM ready event, and you do that in JS, not in WP:</p>\n\n<pre><code>jQuery(document).ready(function(){\n /* your code here */\n});\n</code></pre>\n"
},
{
"answer_id": 289952,
"author": "Espi",
"author_id": 85295,
"author_profile": "https://wordpress.stackexchange.com/users/85295",
"pm_score": 0,
"selected": false,
"text": "<p>I had to move my custom scripts to the bottom of my footer by editing the add_action</p>\n\n<p><code>add_action('wp_enqueue_scripts','loadingscripts', 9999);</code></p>\n\n<p>The 3rd parameter is the priority that your function loads in. giving it a 9999 value will push it to the bottom. if you know the code works on its own my best guess would be that its a plugin's script file that is not playing nice with your script.</p>\n"
}
]
| 2018/01/02 | [
"https://wordpress.stackexchange.com/questions/289929",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/105791/"
]
| ```
if ( ! function_exists( 'loadingscripts' ) ) {
function loadingscripts() {
// Register the script like this for a theme:
wp_register_script( 'custom-js', get_template_directory_uri() . '/js/custom.js', array( 'jquery' ), '1.1', true );
wp_enqueue_script( 'custom-js' );
/* Load the stylesheets. */
// wp_enqueue_style( 'fontawesome', THEMEROOT . '/inc/lib/fontawesome/css/font-awesome.min.css' );
wp_enqueue_style( 'layout', THEMEROOT . '/css/layout.css' );
wp_enqueue_style( 'styles', THEMEROOT . '/css/style.css' );
}
}
add_action('wp_enqueue_scripts','loadingscripts');
```
I think the Javascript is loading before the DOM because in its pure HTML version I was loading the javascript in the footer, but in the WordPress conversion, it doesn't work. What is the fix? | Javascript runs as soon as it's loaded, you need to wait for the DOM ready event, and you do that in JS, not in WP:
```
jQuery(document).ready(function(){
/* your code here */
});
``` |
289,957 | <p><img src="https://i.imgur.com/mT1TUjy.png" alt="Taxonomy description"></p>
<p>I want to add some helpful text to the edit-tags screen describing the proper use of each of my custom taxonomies. </p>
<p>I see <a href="https://codex.wordpress.org/Function_Reference/register_taxonomy" rel="nofollow noreferrer">in the Codex</a> that a description can be added to a custom taxonomy β not to a term, but to the taxonomy itself. That would be a perfect place to put my help text, and I have, but I don't see where that's rendered at all. </p>
<p>From the Codex:</p>
<blockquote>
<p><strong>description</strong>
(string) (optional) Include a description of the taxonomy.
Default: ""</p>
</blockquote>
<p>In my custom taxonomy function's $args array:</p>
<p><code>$args = array(
'description' => 'Some helpful text!'
[other args...]
);</code></p>
<p>Is there a hook for edit-tags that I can use to display the taxonomy's description, or another solution (ACF maybe) for inserting help text here? </p>
| [
{
"answer_id": 289963,
"author": "David Sword",
"author_id": 132362,
"author_profile": "https://wordpress.stackexchange.com/users/132362",
"pm_score": 2,
"selected": true,
"text": "<p>The code for where you've circled can be found in <code>wp-admin/edit-tags.php:295</code></p>\n\n<p>You'll notice there's nothing there. No hooks, no filters. You're out of luck for tapping into that cleanly. </p>\n\n<p>Luckily you can do a duct tape method to still add it with jQuery. You can dynamically put text where you've circled by doing something like:</p>\n\n<pre><code>add_action( 'admin_head', function(){\n global $wp_query;\n $screen = get_current_screen();\n if ($screen->base == 'edit-tags' || $screen->base == 'term') {\n $mytax = get_taxonomy($screen->taxonomy);\n if (!empty($mytax->description)) {\n ?>\n <script>\n jQuery(window).load(function() {\n jQuery('.wrap h1').after(\"<p class='description'><?php echo $mytax->description ?></p>\");\n });\n </script>\n <?php\n }\n }\n});\n</code></pre>\n\n<hr>\n\n<h2>UPDATE</h2>\n\n<p>As you pointed out @Slam, you can use the <code>_pre_add_form</code> and <code>_term_edit_form_top</code> hooks to show the into around the area you're after. To do that, you can cycle through all the taxonomies and dynamically run the actions like so:</p>\n\n<pre><code>add_action( 'admin_init', function(){\n $taxonomies = get_taxonomies(); \n foreach ( $taxonomies as $taxonomy ) {\n add_action(\"{$taxonomy}_pre_add_form\", 'my_plugin_tax_description');\n add_action(\"{$taxonomy}_term_edit_form_top\", 'my_plugin_tax_description');\n }\n});\n\nfunction my_plugin_tax_description() {\n global $wp_query;\n $screen = get_current_screen();\n if ($screen->base == 'edit-tags' || $screen->base == 'term') {\n $mytax = get_taxonomy($screen->taxonomy);\n if (!empty($mytax->description))\n echo \"<p class='description'>{$mytax->description}</p>\";\n }\n}\n</code></pre>\n\n<p>Although <code>_pre_add_form</code> fires in the left column - not directly below the h1 title.</p>\n"
},
{
"answer_id": 315901,
"author": "Skarbona",
"author_id": 151774,
"author_profile": "https://wordpress.stackexchange.com/users/151774",
"pm_score": 0,
"selected": false,
"text": "<p>To @David Sword comments: If you want use standard taxonomy description (in the labels) use this code:</p>\n\n<pre><code>function my_plugin_tax_description() {\n global $wp_query;\n $screen = get_current_screen();\n if ($screen->base == 'edit-tags' || $screen->base == 'term') {\n $mytax = get_taxonomy($screen->taxonomy);\n if (!empty($mytax->labels->description))\n echo \"<p class='description'>{$mytax->labels->description}</p>\";\n }\n}\n</code></pre>\n"
}
]
| 2018/01/02 | [
"https://wordpress.stackexchange.com/questions/289957",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/82256/"
]
| 
I want to add some helpful text to the edit-tags screen describing the proper use of each of my custom taxonomies.
I see [in the Codex](https://codex.wordpress.org/Function_Reference/register_taxonomy) that a description can be added to a custom taxonomy β not to a term, but to the taxonomy itself. That would be a perfect place to put my help text, and I have, but I don't see where that's rendered at all.
From the Codex:
>
> **description**
> (string) (optional) Include a description of the taxonomy.
> Default: ""
>
>
>
In my custom taxonomy function's $args array:
`$args = array(
'description' => 'Some helpful text!'
[other args...]
);`
Is there a hook for edit-tags that I can use to display the taxonomy's description, or another solution (ACF maybe) for inserting help text here? | The code for where you've circled can be found in `wp-admin/edit-tags.php:295`
You'll notice there's nothing there. No hooks, no filters. You're out of luck for tapping into that cleanly.
Luckily you can do a duct tape method to still add it with jQuery. You can dynamically put text where you've circled by doing something like:
```
add_action( 'admin_head', function(){
global $wp_query;
$screen = get_current_screen();
if ($screen->base == 'edit-tags' || $screen->base == 'term') {
$mytax = get_taxonomy($screen->taxonomy);
if (!empty($mytax->description)) {
?>
<script>
jQuery(window).load(function() {
jQuery('.wrap h1').after("<p class='description'><?php echo $mytax->description ?></p>");
});
</script>
<?php
}
}
});
```
---
UPDATE
------
As you pointed out @Slam, you can use the `_pre_add_form` and `_term_edit_form_top` hooks to show the into around the area you're after. To do that, you can cycle through all the taxonomies and dynamically run the actions like so:
```
add_action( 'admin_init', function(){
$taxonomies = get_taxonomies();
foreach ( $taxonomies as $taxonomy ) {
add_action("{$taxonomy}_pre_add_form", 'my_plugin_tax_description');
add_action("{$taxonomy}_term_edit_form_top", 'my_plugin_tax_description');
}
});
function my_plugin_tax_description() {
global $wp_query;
$screen = get_current_screen();
if ($screen->base == 'edit-tags' || $screen->base == 'term') {
$mytax = get_taxonomy($screen->taxonomy);
if (!empty($mytax->description))
echo "<p class='description'>{$mytax->description}</p>";
}
}
```
Although `_pre_add_form` fires in the left column - not directly below the h1 title. |
289,979 | <p>I have a problem with my wordpress site logo. I cannot make the site logo dynamic. </p>
<p>here is my code (displaying logo) which is in header.php page: </p>
<pre><code><a href="<?php echo get_home_url(); ?>" id="logo">
<img src="<?php echo get_template_directory_uri(); ?>/assets/images/logo.png" class="img-responsive" alt="" title="">
</a>
</code></pre>
<p>***** when I want to change it from Customize > Site Identity, here it shows that no logo is attached, yet the logo is displaying successfully at front-end. Even when I try to change it, nothing happens.</p>
<p>Kindly help me to solve this issue. </p>
| [
{
"answer_id": 289980,
"author": "Tarang koradiya",
"author_id": 128666,
"author_profile": "https://wordpress.stackexchange.com/users/128666",
"pm_score": 2,
"selected": true,
"text": "<p>Theme header logo function <code>get_theme_mod( 'custom_logo' );</code></p>\n\n<pre><code>$custom_logo_id = get_theme_mod( 'custom_logo' );\n$image = wp_get_attachment_image_src( $custom_logo_id , 'full' );\necho '<img class=\"header_logo\" src=\"'.$image[0].'\">';\n</code></pre>\n"
},
{
"answer_id": 289982,
"author": "D. Dan",
"author_id": 133528,
"author_profile": "https://wordpress.stackexchange.com/users/133528",
"pm_score": 0,
"selected": false,
"text": "<pre><code>$image = wp_get_attachment_image_src( $custom_logo_id , 'full' );\n</code></pre>\n\n<p>Just change the 'full' to 'thumbnail' or something else. You can also <a href=\"https://developer.wordpress.org/reference/functions/add_image_size/\" rel=\"nofollow noreferrer\">define</a> custom sizes.\nOr you could target it by the class 'header_logo' in css.</p>\n"
},
{
"answer_id": 310614,
"author": "Shikha",
"author_id": 137641,
"author_profile": "https://wordpress.stackexchange.com/users/137641",
"pm_score": 0,
"selected": false,
"text": "<p><strong>Use this code in header.php :</strong> </p>\n\n<pre><code><img src=\"<?php header_image(); ?>\" alt=\"\">\n</code></pre>\n\n<p><strong>Then open site wp-admin :</strong>\nGo to apperence -> customize -> Header Image and upload logo and publish it</p>\n"
}
]
| 2018/01/03 | [
"https://wordpress.stackexchange.com/questions/289979",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/132874/"
]
| I have a problem with my wordpress site logo. I cannot make the site logo dynamic.
here is my code (displaying logo) which is in header.php page:
```
<a href="<?php echo get_home_url(); ?>" id="logo">
<img src="<?php echo get_template_directory_uri(); ?>/assets/images/logo.png" class="img-responsive" alt="" title="">
</a>
```
\*\*\*\*\* when I want to change it from Customize > Site Identity, here it shows that no logo is attached, yet the logo is displaying successfully at front-end. Even when I try to change it, nothing happens.
Kindly help me to solve this issue. | Theme header logo function `get_theme_mod( 'custom_logo' );`
```
$custom_logo_id = get_theme_mod( 'custom_logo' );
$image = wp_get_attachment_image_src( $custom_logo_id , 'full' );
echo '<img class="header_logo" src="'.$image[0].'">';
``` |
289,997 | <p>I have the following in my database</p>
<pre><code>siteurl subdomain.example.com
home subdomain.example.com
</code></pre>
<p>and when I attempt to go to some pages, the pages go to <code>subdomain.example.com/services/subdomain.example.com</code></p>
<p>Is there any reason why this would happen? I can't get into the wp-admin either because of this weird error and I can't understand why it would be happening?</p>
<p>I've attempted to change the values in the database with <code>http://</code> prepended already also.</p>
<p>Any advice is appreciated.</p>
| [
{
"answer_id": 289980,
"author": "Tarang koradiya",
"author_id": 128666,
"author_profile": "https://wordpress.stackexchange.com/users/128666",
"pm_score": 2,
"selected": true,
"text": "<p>Theme header logo function <code>get_theme_mod( 'custom_logo' );</code></p>\n\n<pre><code>$custom_logo_id = get_theme_mod( 'custom_logo' );\n$image = wp_get_attachment_image_src( $custom_logo_id , 'full' );\necho '<img class=\"header_logo\" src=\"'.$image[0].'\">';\n</code></pre>\n"
},
{
"answer_id": 289982,
"author": "D. Dan",
"author_id": 133528,
"author_profile": "https://wordpress.stackexchange.com/users/133528",
"pm_score": 0,
"selected": false,
"text": "<pre><code>$image = wp_get_attachment_image_src( $custom_logo_id , 'full' );\n</code></pre>\n\n<p>Just change the 'full' to 'thumbnail' or something else. You can also <a href=\"https://developer.wordpress.org/reference/functions/add_image_size/\" rel=\"nofollow noreferrer\">define</a> custom sizes.\nOr you could target it by the class 'header_logo' in css.</p>\n"
},
{
"answer_id": 310614,
"author": "Shikha",
"author_id": 137641,
"author_profile": "https://wordpress.stackexchange.com/users/137641",
"pm_score": 0,
"selected": false,
"text": "<p><strong>Use this code in header.php :</strong> </p>\n\n<pre><code><img src=\"<?php header_image(); ?>\" alt=\"\">\n</code></pre>\n\n<p><strong>Then open site wp-admin :</strong>\nGo to apperence -> customize -> Header Image and upload logo and publish it</p>\n"
}
]
| 2018/01/03 | [
"https://wordpress.stackexchange.com/questions/289997",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/134191/"
]
| I have the following in my database
```
siteurl subdomain.example.com
home subdomain.example.com
```
and when I attempt to go to some pages, the pages go to `subdomain.example.com/services/subdomain.example.com`
Is there any reason why this would happen? I can't get into the wp-admin either because of this weird error and I can't understand why it would be happening?
I've attempted to change the values in the database with `http://` prepended already also.
Any advice is appreciated. | Theme header logo function `get_theme_mod( 'custom_logo' );`
```
$custom_logo_id = get_theme_mod( 'custom_logo' );
$image = wp_get_attachment_image_src( $custom_logo_id , 'full' );
echo '<img class="header_logo" src="'.$image[0].'">';
``` |
289,999 | <p>How can i change the recent post widget title programmatically?</p>
<p>I use this code in my footer.php to add recent posts widget.</p>
<pre><code><?php the_widget( 'WP_Widget_Recent_Posts' ); ?>
</code></pre>
| [
{
"answer_id": 290002,
"author": "Mostafa Norzade",
"author_id": 131388,
"author_profile": "https://wordpress.stackexchange.com/users/131388",
"pm_score": 1,
"selected": false,
"text": "<p>One of the ways is:</p>\n\n<p>1) Rename the Widget class name</p>\n\n<p>2) Modify the Widget class</p>\n\n<p>3) Register your Widget:</p>\n\n<pre><code>function wpse97413_register_custom_widgets() {\n register_widget( 'wpse97411_Widget_Recent_Posts' );\n }\n add_action( 'widgets_init', 'wpse97413_register_custom_widgets' );\n</code></pre>\n\n<p><a href=\"https://codex.wordpress.org/Widgets_API\" rel=\"nofollow noreferrer\">Developing Widgets\n</a></p>\n"
},
{
"answer_id": 290010,
"author": "Sid",
"author_id": 110516,
"author_profile": "https://wordpress.stackexchange.com/users/110516",
"pm_score": 3,
"selected": true,
"text": "<p>I had a similar situation. Add the following code to your functions.php and see if it works for you.</p>\n\n<pre><code>function my_widget_title($title, $instance, $id_base) {\n if ( 'recent-posts' == $id_base) {\n return __('New Title');\n } \n else {\n return $title;\n } \n}\n\nadd_filter ( 'widget_title' , 'my_widget_title', 10, 3); \n</code></pre>\n\n<blockquote>\n <p>Note: this will change the title of all the \"Recent Post\" widgets.</p>\n</blockquote>\n"
},
{
"answer_id": 290027,
"author": "jimihenrik",
"author_id": 64625,
"author_profile": "https://wordpress.stackexchange.com/users/64625",
"pm_score": 0,
"selected": false,
"text": "<p>Just for the sake of completion:</p>\n\n<p>As you can see <a href=\"https://developer.wordpress.org/reference/classes/wp_widget_recent_posts/widget/\" rel=\"nofollow noreferrer\">here</a> you can pass the widget multitude of things straight in the code too. Let's say you want the widget to show three posts, with custom title and you want to wrap the title in h2+span tags for styling purposes you could do this:</p>\n\n<pre><code>the_widget( 'WP_Widget_Recent_Posts',\n array ( 'title' => 'Three of dem posts', 'number' => 3 ),\n array ( 'before_title' => '<h2 class=\"block-title\"><span>', 'after_title' => '</span></h2>' )\n);\n</code></pre>\n\n<p>Which would produce just that.</p>\n\n<p>You can also of course just pass only the 'title', which would give the default amount of 5 posts on the widget.</p>\n"
}
]
| 2018/01/03 | [
"https://wordpress.stackexchange.com/questions/289999",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/132099/"
]
| How can i change the recent post widget title programmatically?
I use this code in my footer.php to add recent posts widget.
```
<?php the_widget( 'WP_Widget_Recent_Posts' ); ?>
``` | I had a similar situation. Add the following code to your functions.php and see if it works for you.
```
function my_widget_title($title, $instance, $id_base) {
if ( 'recent-posts' == $id_base) {
return __('New Title');
}
else {
return $title;
}
}
add_filter ( 'widget_title' , 'my_widget_title', 10, 3);
```
>
> Note: this will change the title of all the "Recent Post" widgets.
>
>
> |
290,005 | <p>I would like to generate a simple text report for a Wordpress instance listing:</p>
<ul>
<li>Wordpress version</li>
<li>plugins installed (version and whether enabled)</li>
<li>themes and child themes installed (version and whether enabled)</li>
</ul>
<p>I can get this information from the Dashboard, but is there a way to get it programmatically (with WP CLI, WP API or regular command line calls)?</p>
| [
{
"answer_id": 290020,
"author": "lofidevops",
"author_id": 31388,
"author_profile": "https://wordpress.stackexchange.com/users/31388",
"pm_score": 2,
"selected": false,
"text": "<p>Using WP CLI, you can record Wordpress version using:</p>\n\n<pre><code>wp core version --extra --path=\"$SITEPATH\" > wp-report.txt\n</code></pre>\n\n<p>and append a list of plugins (with status and version):</p>\n\n<pre><code>wp plugin list --path=\"$SITEPATH\" >> wp-report.txt\n</code></pre>\n\n<p>and append a list of themes (with status and version) using:</p>\n\n<pre><code>wp theme list --path=\"$SITEPATH\" >> wp-report.txt\n</code></pre>\n\n<p><strong>Further reading:</strong></p>\n\n<ul>\n<li><a href=\"https://developer.wordpress.org/cli/commands/core/version/\" rel=\"nofollow noreferrer\">https://developer.wordpress.org/cli/commands/core/version/</a></li>\n<li><a href=\"https://developer.wordpress.org/cli/commands/plugin/list/\" rel=\"nofollow noreferrer\">https://developer.wordpress.org/cli/commands/plugin/list/</a></li>\n<li><a href=\"https://developer.wordpress.org/cli/commands/theme/list/\" rel=\"nofollow noreferrer\">https://developer.wordpress.org/cli/commands/theme/list/</a></li>\n</ul>\n"
},
{
"answer_id": 290021,
"author": "majick",
"author_id": 76440,
"author_profile": "https://wordpress.stackexchange.com/users/76440",
"pm_score": 1,
"selected": false,
"text": "<p>WP CLI is probably the best for this:</p>\n\n<p>WordPress Version:</p>\n\n<pre><code>wp core version --path=\"$SITEPATH\" > wp-report.txt\n</code></pre>\n\n<p>List Plugins:</p>\n\n<pre><code>wp plugin list --path=\"$SITEPATH\" >> wp-report.txt\n</code></pre>\n\n<p>List Themes: </p>\n\n<pre><code>wp theme list --path=\"$SITEPATH\" >> wp-report.txt\n</code></pre>\n\n<p>(replacing $SITEPATH with the WordPress installation directory.)</p>\n\n<p>Reference: <a href=\"https://developer.wordpress.org/cli/commands/\" rel=\"nofollow noreferrer\">https://developer.wordpress.org/cli/commands/</a></p>\n"
}
]
| 2018/01/03 | [
"https://wordpress.stackexchange.com/questions/290005",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/31388/"
]
| I would like to generate a simple text report for a Wordpress instance listing:
* Wordpress version
* plugins installed (version and whether enabled)
* themes and child themes installed (version and whether enabled)
I can get this information from the Dashboard, but is there a way to get it programmatically (with WP CLI, WP API or regular command line calls)? | Using WP CLI, you can record Wordpress version using:
```
wp core version --extra --path="$SITEPATH" > wp-report.txt
```
and append a list of plugins (with status and version):
```
wp plugin list --path="$SITEPATH" >> wp-report.txt
```
and append a list of themes (with status and version) using:
```
wp theme list --path="$SITEPATH" >> wp-report.txt
```
**Further reading:**
* <https://developer.wordpress.org/cli/commands/core/version/>
* <https://developer.wordpress.org/cli/commands/plugin/list/>
* <https://developer.wordpress.org/cli/commands/theme/list/> |
290,015 | <p>I am developing a free theme and users can download it from WordPress.org. I am working on pro version of the same theme. What should be the name of the pro version's folder? </p>
<p>My theme's name is BizPoint. If I name the pro version's folder as 'BizPoint-Pro', whatever changes the user has done using customizer, are lost. If I use pro version's folder name as 'BizPoint', users won't be able to install pro version without deleting the free theme.</p>
<p>How is this conflict handled?</p>
| [
{
"answer_id": 290020,
"author": "lofidevops",
"author_id": 31388,
"author_profile": "https://wordpress.stackexchange.com/users/31388",
"pm_score": 2,
"selected": false,
"text": "<p>Using WP CLI, you can record Wordpress version using:</p>\n\n<pre><code>wp core version --extra --path=\"$SITEPATH\" > wp-report.txt\n</code></pre>\n\n<p>and append a list of plugins (with status and version):</p>\n\n<pre><code>wp plugin list --path=\"$SITEPATH\" >> wp-report.txt\n</code></pre>\n\n<p>and append a list of themes (with status and version) using:</p>\n\n<pre><code>wp theme list --path=\"$SITEPATH\" >> wp-report.txt\n</code></pre>\n\n<p><strong>Further reading:</strong></p>\n\n<ul>\n<li><a href=\"https://developer.wordpress.org/cli/commands/core/version/\" rel=\"nofollow noreferrer\">https://developer.wordpress.org/cli/commands/core/version/</a></li>\n<li><a href=\"https://developer.wordpress.org/cli/commands/plugin/list/\" rel=\"nofollow noreferrer\">https://developer.wordpress.org/cli/commands/plugin/list/</a></li>\n<li><a href=\"https://developer.wordpress.org/cli/commands/theme/list/\" rel=\"nofollow noreferrer\">https://developer.wordpress.org/cli/commands/theme/list/</a></li>\n</ul>\n"
},
{
"answer_id": 290021,
"author": "majick",
"author_id": 76440,
"author_profile": "https://wordpress.stackexchange.com/users/76440",
"pm_score": 1,
"selected": false,
"text": "<p>WP CLI is probably the best for this:</p>\n\n<p>WordPress Version:</p>\n\n<pre><code>wp core version --path=\"$SITEPATH\" > wp-report.txt\n</code></pre>\n\n<p>List Plugins:</p>\n\n<pre><code>wp plugin list --path=\"$SITEPATH\" >> wp-report.txt\n</code></pre>\n\n<p>List Themes: </p>\n\n<pre><code>wp theme list --path=\"$SITEPATH\" >> wp-report.txt\n</code></pre>\n\n<p>(replacing $SITEPATH with the WordPress installation directory.)</p>\n\n<p>Reference: <a href=\"https://developer.wordpress.org/cli/commands/\" rel=\"nofollow noreferrer\">https://developer.wordpress.org/cli/commands/</a></p>\n"
}
]
| 2018/01/03 | [
"https://wordpress.stackexchange.com/questions/290015",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/128132/"
]
| I am developing a free theme and users can download it from WordPress.org. I am working on pro version of the same theme. What should be the name of the pro version's folder?
My theme's name is BizPoint. If I name the pro version's folder as 'BizPoint-Pro', whatever changes the user has done using customizer, are lost. If I use pro version's folder name as 'BizPoint', users won't be able to install pro version without deleting the free theme.
How is this conflict handled? | Using WP CLI, you can record Wordpress version using:
```
wp core version --extra --path="$SITEPATH" > wp-report.txt
```
and append a list of plugins (with status and version):
```
wp plugin list --path="$SITEPATH" >> wp-report.txt
```
and append a list of themes (with status and version) using:
```
wp theme list --path="$SITEPATH" >> wp-report.txt
```
**Further reading:**
* <https://developer.wordpress.org/cli/commands/core/version/>
* <https://developer.wordpress.org/cli/commands/plugin/list/>
* <https://developer.wordpress.org/cli/commands/theme/list/> |
290,018 | <p>I am testing plugin upgrades on a staging instance before applying them to production. But if there are any delays in this process, I may end up being prompted to upgrade to a newer, untested version on production.</p>
<p>If prompted to upgrade a plugin, how can I choose an intermediary update, rather than the latest?</p>
| [
{
"answer_id": 290019,
"author": "kero",
"author_id": 108180,
"author_profile": "https://wordpress.stackexchange.com/users/108180",
"pm_score": 6,
"selected": true,
"text": "<p>Using WP-CLI you can specify this as described in the <a href=\"https://developer.wordpress.org/cli/commands/plugin/update/\" rel=\"noreferrer\">official documentation</a>.</p>\n\n<pre><code>$ wp plugin update <plugin>\n</code></pre>\n\n<p>Using either of the following arguments</p>\n\n<pre><code>--minor\n</code></pre>\n\n<blockquote>\n <p>Only perform updates for minor releases (e.g. from 1.3 to 1.4 instead of 2.0)</p>\n</blockquote>\n\n<pre><code>--patch\n</code></pre>\n\n<blockquote>\n <p>Only perform updates for patch releases (e.g. from 1.3 to 1.3.3 instead of 1.4)</p>\n</blockquote>\n\n<pre><code>--version=<version>\n</code></pre>\n\n<blockquote>\n <p>If set, the plugin will be updated to the specified version.</p>\n</blockquote>\n"
},
{
"answer_id": 291669,
"author": "Liam Stewart",
"author_id": 121955,
"author_profile": "https://wordpress.stackexchange.com/users/121955",
"pm_score": 2,
"selected": false,
"text": "<p>You can also download specific versions from the plugin's SVN.</p>\n<p>For example, imagine you wanted a specific version of the Yoast SEO plugin.</p>\n<p>The plugin page for Yoast is is:</p>\n<p><a href=\"https://wordpress.org/plugins/%60wordpress-seo%60/\" rel=\"nofollow noreferrer\">https://wordpress.org/plugins/`wordpress-seo`/</a></p>\n<p>Note the highlighted section of the URI <code>wordpress-seo</code></p>\n<p>The SVN/Repo URI will be (notice the URI slug includes the highlighted section from above):</p>\n<p><a href=\"https://plugins.svn.wordpress.org/%60wordpress-seo%60/tags/\" rel=\"nofollow noreferrer\">https://plugins.svn.wordpress.org/`wordpress-seo`/tags/</a></p>\n<p>The <code>tags</code> folder lists all the versions.</p>\n"
},
{
"answer_id": 393140,
"author": "AFOC",
"author_id": 124520,
"author_profile": "https://wordpress.stackexchange.com/users/124520",
"pm_score": 1,
"selected": false,
"text": "<p>The most straightforward no cli method of easily upgrading / downgrading a plugin to a specific version:</p>\n<ol>\n<li>Click on "advanced view" on the right column of the plugin's page under the list of info - it will take you to a url like <code>https://wordpress.org/plugins/<plugin>/advanced/</code></li>\n<li>Find the "previous versions" section at the very bottom, select the version you want from the dropdown and download the zip file</li>\n<li>Remove the current version's folder from <code>wp-content/plugins</code></li>\n<li>Extract the zip you just downloaded and copy the folder into <code>wp-content/plugins</code></li>\n<li>Verify on your site at <code>www.yoursite.com/wp-admin/plugins.php</code> that the version you wanted is now listed</li>\n</ol>\n<p>That's it.</p>\n"
}
]
| 2018/01/03 | [
"https://wordpress.stackexchange.com/questions/290018",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/31388/"
]
| I am testing plugin upgrades on a staging instance before applying them to production. But if there are any delays in this process, I may end up being prompted to upgrade to a newer, untested version on production.
If prompted to upgrade a plugin, how can I choose an intermediary update, rather than the latest? | Using WP-CLI you can specify this as described in the [official documentation](https://developer.wordpress.org/cli/commands/plugin/update/).
```
$ wp plugin update <plugin>
```
Using either of the following arguments
```
--minor
```
>
> Only perform updates for minor releases (e.g. from 1.3 to 1.4 instead of 2.0)
>
>
>
```
--patch
```
>
> Only perform updates for patch releases (e.g. from 1.3 to 1.3.3 instead of 1.4)
>
>
>
```
--version=<version>
```
>
> If set, the plugin will be updated to the specified version.
>
>
> |
290,022 | <p>I'm trying to configure the WordPress cookie expiration time, but for some reason it's not working. I went here:</p>
<p><a href="https://developer.wordpress.org/reference/hooks/auth_cookie_expiration/" rel="nofollow noreferrer">https://developer.wordpress.org/reference/hooks/auth_cookie_expiration/</a></p>
<p>And put the following hook based on the doc:</p>
<pre><code>function init() {
// ...
$expiration = 60;
apply_filters( 'auth_cookie_expiration', $expiration );
}
</code></pre>
<p>This code is called from a hook in my plugin's constructor:</p>
<pre><code>add_action( 'init', array( $this, 'init' ) );
</code></pre>
<p>And I have verified that it runs.</p>
<p>I expected this to produce a cookie that expires in 60 seconds, but it doesn't. Instead it sets a regular expiration time of 48 hours (WP default). I suspect this might be because when the user actually logs in, it doesn't create this expiration date, and running this function later has no effect. I haven't yet figured out how to make it work though. Any help appreciated.</p>
| [
{
"answer_id": 290024,
"author": "birgire",
"author_id": 26350,
"author_profile": "https://wordpress.stackexchange.com/users/26350",
"pm_score": 2,
"selected": true,
"text": "<p>Note that you're not adding any filter callback with:</p>\n\n<pre><code>apply_filters( 'auth_cookie_expiration', $expiration );\n</code></pre>\n\n<p>Instead use: </p>\n\n<pre><code>add_filter( 'auth_cookie_expiration', $callback, 10, 3 );\n</code></pre>\n\n<p>where <code>$callback</code> is the appropriate filter callback that modifies the expiration.</p>\n\n<p>Here's an example</p>\n\n<pre><code>add_filter( 'auth_cookie_expiration', function( $length, $user_id, $remember ) {\n return $length; // adjust this to your needs.\n}, 10, 3 );\n</code></pre>\n\n<p>or to fit with your current class setup:</p>\n\n<pre><code>add_filter( 'auth_cookie_expiration', [ $this, 'set_auth_cookie_expiration' ], 10, 3 );\n</code></pre>\n\n<p>where <code>set_auth_cookie_expiration()</code> is the appropriate method, e.g.:</p>\n\n<pre><code>public function set_auth_cookie_expiration ( $length, $user_id, $remember ) \n{\n return $length; // adjust this to your needs.\n}\n</code></pre>\n"
},
{
"answer_id": 320211,
"author": "Ankit Sewadik",
"author_id": 154388,
"author_profile": "https://wordpress.stackexchange.com/users/154388",
"pm_score": -1,
"selected": false,
"text": "<pre><code>add_filter( 'auth_cookie_expiration', 'keep_me_logged_in_for_1_year' );\n\nfunction keep_me_logged_in_for_1_year( $expirein ) {\n return 31556926; // 1 year in seconds\n}\n</code></pre>\n"
}
]
| 2018/01/03 | [
"https://wordpress.stackexchange.com/questions/290022",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/33019/"
]
| I'm trying to configure the WordPress cookie expiration time, but for some reason it's not working. I went here:
<https://developer.wordpress.org/reference/hooks/auth_cookie_expiration/>
And put the following hook based on the doc:
```
function init() {
// ...
$expiration = 60;
apply_filters( 'auth_cookie_expiration', $expiration );
}
```
This code is called from a hook in my plugin's constructor:
```
add_action( 'init', array( $this, 'init' ) );
```
And I have verified that it runs.
I expected this to produce a cookie that expires in 60 seconds, but it doesn't. Instead it sets a regular expiration time of 48 hours (WP default). I suspect this might be because when the user actually logs in, it doesn't create this expiration date, and running this function later has no effect. I haven't yet figured out how to make it work though. Any help appreciated. | Note that you're not adding any filter callback with:
```
apply_filters( 'auth_cookie_expiration', $expiration );
```
Instead use:
```
add_filter( 'auth_cookie_expiration', $callback, 10, 3 );
```
where `$callback` is the appropriate filter callback that modifies the expiration.
Here's an example
```
add_filter( 'auth_cookie_expiration', function( $length, $user_id, $remember ) {
return $length; // adjust this to your needs.
}, 10, 3 );
```
or to fit with your current class setup:
```
add_filter( 'auth_cookie_expiration', [ $this, 'set_auth_cookie_expiration' ], 10, 3 );
```
where `set_auth_cookie_expiration()` is the appropriate method, e.g.:
```
public function set_auth_cookie_expiration ( $length, $user_id, $remember )
{
return $length; // adjust this to your needs.
}
``` |
290,030 | <p>I have an <code>add_filter</code> function for the <code>auth_cookie_expiration</code> hook. This hook accepts three parameters. However, I am interested in passing it more parameters. For example:</p>
<pre><code>add_filter( 'auth_cookie_expiration', 'get_expiration', 10, 5 );
</code></pre>
<p>This would be possible with <code>apply_filter</code>, but the <code>add_filter</code> function is called once, which makes it throw an error:</p>
<pre><code>PHP Fatal error: Uncaught ArgumentCountError: Too few arguments to function get_expiration(), 3 passed in ... and exactly 5 expected
</code></pre>
<p>I got around this using closures, but it seems like a completely ridiculous way to do this:</p>
<pre><code>add_filter( 'auth_cookie_expiration', function() use ($param1, $param2) { return get_expiration(null, null, null, $param1, $param2); } , 10, 3 );
</code></pre>
<p>Is there a proper/more elegant way to make it accept additional parameters (even better, the params I want in place of the default ones)? Am I misunderstanding how <code>add_filter</code> is supposed to work?</p>
<p>For the sake of example, suppose <code>get_expiration</code> looks like this:</p>
<pre><code>function get_expiration( $length, $user_id, $remember, $param1, $param2 )
{
return $param1 + $param2;
}
</code></pre>
| [
{
"answer_id": 290076,
"author": "Frank P. Walentynowicz",
"author_id": 32851,
"author_profile": "https://wordpress.stackexchange.com/users/32851",
"pm_score": 2,
"selected": false,
"text": "<blockquote>\n <p>Am I misunderstanding how add_filter is supposed to work?</p>\n</blockquote>\n\n<p>Yes, you are. </p>\n\n<p>The function ( aka callback function ), specified by name, in the second parameter of <code>add_filter()</code>, <strong>NEVER</strong> passes <strong>ANY</strong> parameters. It accepts parameters passed by <code>apply_filters()</code>. The number of these parameters, and their meaning is defined by <code>apply_filters()</code>. The callback function <strong>MUST</strong> accept at least the first parameter, past the hook name. It <strong>MUST</strong>, also, return modified ( or not ) value for this first parameter. </p>\n"
},
{
"answer_id": 344847,
"author": "Ryszard JΔdraszyk",
"author_id": 153903,
"author_profile": "https://wordpress.stackexchange.com/users/153903",
"pm_score": 3,
"selected": false,
"text": "<p>The second parameter in <code>add_filter</code> is a function with <strong>accepted arguments</strong>, not returned values.</p>\n\n<p>This is an example how I pass my custom array <code>$args</code> to change an existing array <code>$filter_args</code>:</p>\n\n<pre><code>add_filter( 'woocommerce_dropdown_variation_attribute_options_args', function( $filter_args ) use ( $args ) {\n return eswc_var_dropdown_args( $filter_args, $args );\n }\n);\n\nfunction eswc_var_dropdown_args( $filter_args, $args ) {\n $filter_args['show_option_none'] = $args['var_select_text'];\n return $filter_args;\n}\n</code></pre>\n"
},
{
"answer_id": 360301,
"author": "Ynhockey",
"author_id": 33019,
"author_profile": "https://wordpress.stackexchange.com/users/33019",
"pm_score": 0,
"selected": false,
"text": "<p>After just using my original \"solution\" for a while, I have returned to this problem with a bit more time to figure out what WordPress actually does.</p>\n\n<p>Firstly it should be noted that to directly pass a parameter to an <code>add_filter</code> function, the only reasonable way is the one in my original question.</p>\n\n<p>However, more often than not, it is possible to solve the larger problem better by passing a parameter to the function calling <code>apply_filters</code> in WordPress or the plugin you're trying to hook into.</p>\n\n<p>For example, <code>apply_filters( 'auth_cookie_expiration' )</code>, in any meaningful way for hooking, is called in WordPress inside <code>wp_set_auth_cookie</code>, which accepts the same parameters ( <code>$user_id, $remember</code> ), so calling <code>wp_set_auth_cookie()</code> (likely done anyway for any session manipulation) allows the eventual passing of parameters to <code>add_filter</code>. For example:</p>\n\n<pre><code>add_filter( 'auth_cookie_expiration', array( 'get_session_expiration' ), 10, 3 );\n\n// ...\n\nwp_set_auth_cookie( $user_id, $is_remember_me );\n\n// ...\n\nfunction get_session_expiration( $expiration, $user_id, $remember ) {\n // ...\n return $some_calculated_expiration;\n}\n</code></pre>\n\n<p>This works in multiple cases I have found where filter hooks are available.</p>\n"
}
]
| 2018/01/03 | [
"https://wordpress.stackexchange.com/questions/290030",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/33019/"
]
| I have an `add_filter` function for the `auth_cookie_expiration` hook. This hook accepts three parameters. However, I am interested in passing it more parameters. For example:
```
add_filter( 'auth_cookie_expiration', 'get_expiration', 10, 5 );
```
This would be possible with `apply_filter`, but the `add_filter` function is called once, which makes it throw an error:
```
PHP Fatal error: Uncaught ArgumentCountError: Too few arguments to function get_expiration(), 3 passed in ... and exactly 5 expected
```
I got around this using closures, but it seems like a completely ridiculous way to do this:
```
add_filter( 'auth_cookie_expiration', function() use ($param1, $param2) { return get_expiration(null, null, null, $param1, $param2); } , 10, 3 );
```
Is there a proper/more elegant way to make it accept additional parameters (even better, the params I want in place of the default ones)? Am I misunderstanding how `add_filter` is supposed to work?
For the sake of example, suppose `get_expiration` looks like this:
```
function get_expiration( $length, $user_id, $remember, $param1, $param2 )
{
return $param1 + $param2;
}
``` | The second parameter in `add_filter` is a function with **accepted arguments**, not returned values.
This is an example how I pass my custom array `$args` to change an existing array `$filter_args`:
```
add_filter( 'woocommerce_dropdown_variation_attribute_options_args', function( $filter_args ) use ( $args ) {
return eswc_var_dropdown_args( $filter_args, $args );
}
);
function eswc_var_dropdown_args( $filter_args, $args ) {
$filter_args['show_option_none'] = $args['var_select_text'];
return $filter_args;
}
``` |
290,036 | <p>I don't know why the SHOW ALL is not displaying. It needs to display when the there are more than 6 posts under BOOKS. </p>
<pre><code><?php
for($k=0;$k<count($results);$k++){
$ID = $results[$k]['book_id'];
$args = array('p' => $ID, 'post_type' => 'attraction');
$loop = new WP_Query($args);
$book_img = get_the_post_thumbnail( $ID, 'medium', array( 'class' => 'alignleft' ) );
if ($book_img) {
//NOTHING TO SHOW
}
}
?>
<?php
$args = array(
'post_type' => 'book',
'showposts'=> 6,
'tax_query' => array(
array(
'taxonomy' => 'destinations',
'terms' => $current_term->term_id,
)
)
);
$books = new WP_Query($args);
echo '<ul class="discover-books country-details">';
if ( $books->have_posts() ) {
while ( $books->have_posts() ) : $books->the_post();
$book_img = get_the_post_thumbnail( get_the_ID(), 'medium', array( 'class' => 'alignleft' ) );
echo '<li class="discover-single-box"><span class="discover-cell imageFit dimensions_img"><a href="'.get_permalink().'">'.$book_img.'</a><span class="bottom-content"><a href="'.get_permalink().'">'.get_the_title().'</a></span> </span></li>';
endwhile;
}
echo '</ul>';
if(count($results) > 6) {
echo '<div class="show-more"><a href="'.get_site_url().'/book?id='.base64_encode($current_term->term_id).'">SHOW ALL</a></div>';
}
?>
</code></pre>
| [
{
"answer_id": 290076,
"author": "Frank P. Walentynowicz",
"author_id": 32851,
"author_profile": "https://wordpress.stackexchange.com/users/32851",
"pm_score": 2,
"selected": false,
"text": "<blockquote>\n <p>Am I misunderstanding how add_filter is supposed to work?</p>\n</blockquote>\n\n<p>Yes, you are. </p>\n\n<p>The function ( aka callback function ), specified by name, in the second parameter of <code>add_filter()</code>, <strong>NEVER</strong> passes <strong>ANY</strong> parameters. It accepts parameters passed by <code>apply_filters()</code>. The number of these parameters, and their meaning is defined by <code>apply_filters()</code>. The callback function <strong>MUST</strong> accept at least the first parameter, past the hook name. It <strong>MUST</strong>, also, return modified ( or not ) value for this first parameter. </p>\n"
},
{
"answer_id": 344847,
"author": "Ryszard JΔdraszyk",
"author_id": 153903,
"author_profile": "https://wordpress.stackexchange.com/users/153903",
"pm_score": 3,
"selected": false,
"text": "<p>The second parameter in <code>add_filter</code> is a function with <strong>accepted arguments</strong>, not returned values.</p>\n\n<p>This is an example how I pass my custom array <code>$args</code> to change an existing array <code>$filter_args</code>:</p>\n\n<pre><code>add_filter( 'woocommerce_dropdown_variation_attribute_options_args', function( $filter_args ) use ( $args ) {\n return eswc_var_dropdown_args( $filter_args, $args );\n }\n);\n\nfunction eswc_var_dropdown_args( $filter_args, $args ) {\n $filter_args['show_option_none'] = $args['var_select_text'];\n return $filter_args;\n}\n</code></pre>\n"
},
{
"answer_id": 360301,
"author": "Ynhockey",
"author_id": 33019,
"author_profile": "https://wordpress.stackexchange.com/users/33019",
"pm_score": 0,
"selected": false,
"text": "<p>After just using my original \"solution\" for a while, I have returned to this problem with a bit more time to figure out what WordPress actually does.</p>\n\n<p>Firstly it should be noted that to directly pass a parameter to an <code>add_filter</code> function, the only reasonable way is the one in my original question.</p>\n\n<p>However, more often than not, it is possible to solve the larger problem better by passing a parameter to the function calling <code>apply_filters</code> in WordPress or the plugin you're trying to hook into.</p>\n\n<p>For example, <code>apply_filters( 'auth_cookie_expiration' )</code>, in any meaningful way for hooking, is called in WordPress inside <code>wp_set_auth_cookie</code>, which accepts the same parameters ( <code>$user_id, $remember</code> ), so calling <code>wp_set_auth_cookie()</code> (likely done anyway for any session manipulation) allows the eventual passing of parameters to <code>add_filter</code>. For example:</p>\n\n<pre><code>add_filter( 'auth_cookie_expiration', array( 'get_session_expiration' ), 10, 3 );\n\n// ...\n\nwp_set_auth_cookie( $user_id, $is_remember_me );\n\n// ...\n\nfunction get_session_expiration( $expiration, $user_id, $remember ) {\n // ...\n return $some_calculated_expiration;\n}\n</code></pre>\n\n<p>This works in multiple cases I have found where filter hooks are available.</p>\n"
}
]
| 2018/01/03 | [
"https://wordpress.stackexchange.com/questions/290036",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/134208/"
]
| I don't know why the SHOW ALL is not displaying. It needs to display when the there are more than 6 posts under BOOKS.
```
<?php
for($k=0;$k<count($results);$k++){
$ID = $results[$k]['book_id'];
$args = array('p' => $ID, 'post_type' => 'attraction');
$loop = new WP_Query($args);
$book_img = get_the_post_thumbnail( $ID, 'medium', array( 'class' => 'alignleft' ) );
if ($book_img) {
//NOTHING TO SHOW
}
}
?>
<?php
$args = array(
'post_type' => 'book',
'showposts'=> 6,
'tax_query' => array(
array(
'taxonomy' => 'destinations',
'terms' => $current_term->term_id,
)
)
);
$books = new WP_Query($args);
echo '<ul class="discover-books country-details">';
if ( $books->have_posts() ) {
while ( $books->have_posts() ) : $books->the_post();
$book_img = get_the_post_thumbnail( get_the_ID(), 'medium', array( 'class' => 'alignleft' ) );
echo '<li class="discover-single-box"><span class="discover-cell imageFit dimensions_img"><a href="'.get_permalink().'">'.$book_img.'</a><span class="bottom-content"><a href="'.get_permalink().'">'.get_the_title().'</a></span> </span></li>';
endwhile;
}
echo '</ul>';
if(count($results) > 6) {
echo '<div class="show-more"><a href="'.get_site_url().'/book?id='.base64_encode($current_term->term_id).'">SHOW ALL</a></div>';
}
?>
``` | The second parameter in `add_filter` is a function with **accepted arguments**, not returned values.
This is an example how I pass my custom array `$args` to change an existing array `$filter_args`:
```
add_filter( 'woocommerce_dropdown_variation_attribute_options_args', function( $filter_args ) use ( $args ) {
return eswc_var_dropdown_args( $filter_args, $args );
}
);
function eswc_var_dropdown_args( $filter_args, $args ) {
$filter_args['show_option_none'] = $args['var_select_text'];
return $filter_args;
}
``` |
290,037 | <pre><code><img src="<?php echo get_bloginfo('template_url') ?>/images/logo.png"/>
</code></pre>
<p>Is the above still a relevant method of embedding images in the Wordpress theme or an obsolete?</p>
<p>If obsolete then what will be the correct method?</p>
<p>someone questioned me today that I am not doing it correctly?</p>
| [
{
"answer_id": 290076,
"author": "Frank P. Walentynowicz",
"author_id": 32851,
"author_profile": "https://wordpress.stackexchange.com/users/32851",
"pm_score": 2,
"selected": false,
"text": "<blockquote>\n <p>Am I misunderstanding how add_filter is supposed to work?</p>\n</blockquote>\n\n<p>Yes, you are. </p>\n\n<p>The function ( aka callback function ), specified by name, in the second parameter of <code>add_filter()</code>, <strong>NEVER</strong> passes <strong>ANY</strong> parameters. It accepts parameters passed by <code>apply_filters()</code>. The number of these parameters, and their meaning is defined by <code>apply_filters()</code>. The callback function <strong>MUST</strong> accept at least the first parameter, past the hook name. It <strong>MUST</strong>, also, return modified ( or not ) value for this first parameter. </p>\n"
},
{
"answer_id": 344847,
"author": "Ryszard JΔdraszyk",
"author_id": 153903,
"author_profile": "https://wordpress.stackexchange.com/users/153903",
"pm_score": 3,
"selected": false,
"text": "<p>The second parameter in <code>add_filter</code> is a function with <strong>accepted arguments</strong>, not returned values.</p>\n\n<p>This is an example how I pass my custom array <code>$args</code> to change an existing array <code>$filter_args</code>:</p>\n\n<pre><code>add_filter( 'woocommerce_dropdown_variation_attribute_options_args', function( $filter_args ) use ( $args ) {\n return eswc_var_dropdown_args( $filter_args, $args );\n }\n);\n\nfunction eswc_var_dropdown_args( $filter_args, $args ) {\n $filter_args['show_option_none'] = $args['var_select_text'];\n return $filter_args;\n}\n</code></pre>\n"
},
{
"answer_id": 360301,
"author": "Ynhockey",
"author_id": 33019,
"author_profile": "https://wordpress.stackexchange.com/users/33019",
"pm_score": 0,
"selected": false,
"text": "<p>After just using my original \"solution\" for a while, I have returned to this problem with a bit more time to figure out what WordPress actually does.</p>\n\n<p>Firstly it should be noted that to directly pass a parameter to an <code>add_filter</code> function, the only reasonable way is the one in my original question.</p>\n\n<p>However, more often than not, it is possible to solve the larger problem better by passing a parameter to the function calling <code>apply_filters</code> in WordPress or the plugin you're trying to hook into.</p>\n\n<p>For example, <code>apply_filters( 'auth_cookie_expiration' )</code>, in any meaningful way for hooking, is called in WordPress inside <code>wp_set_auth_cookie</code>, which accepts the same parameters ( <code>$user_id, $remember</code> ), so calling <code>wp_set_auth_cookie()</code> (likely done anyway for any session manipulation) allows the eventual passing of parameters to <code>add_filter</code>. For example:</p>\n\n<pre><code>add_filter( 'auth_cookie_expiration', array( 'get_session_expiration' ), 10, 3 );\n\n// ...\n\nwp_set_auth_cookie( $user_id, $is_remember_me );\n\n// ...\n\nfunction get_session_expiration( $expiration, $user_id, $remember ) {\n // ...\n return $some_calculated_expiration;\n}\n</code></pre>\n\n<p>This works in multiple cases I have found where filter hooks are available.</p>\n"
}
]
| 2018/01/03 | [
"https://wordpress.stackexchange.com/questions/290037",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/105791/"
]
| ```
<img src="<?php echo get_bloginfo('template_url') ?>/images/logo.png"/>
```
Is the above still a relevant method of embedding images in the Wordpress theme or an obsolete?
If obsolete then what will be the correct method?
someone questioned me today that I am not doing it correctly? | The second parameter in `add_filter` is a function with **accepted arguments**, not returned values.
This is an example how I pass my custom array `$args` to change an existing array `$filter_args`:
```
add_filter( 'woocommerce_dropdown_variation_attribute_options_args', function( $filter_args ) use ( $args ) {
return eswc_var_dropdown_args( $filter_args, $args );
}
);
function eswc_var_dropdown_args( $filter_args, $args ) {
$filter_args['show_option_none'] = $args['var_select_text'];
return $filter_args;
}
``` |
290,075 | <p>Is there a way to bold a specific word or part of a widget title? For example the title "Foo Bar", "Foo" here would be bold.</p>
<p>I tried doing the following, but the span gets outputted in the title:</p>
<pre><code>add_filter( 'widget_title', 'test', 10, 1);
function test( $content ) {
$test = explode(' ', $content);
if ( !empty($test[1] ) ) {
$title = '<span class="this_is_bold">' . $test[0] . '</span>';
$title = $title . ' ' . $test[1];
}
return $title;
}
</code></pre>
| [
{
"answer_id": 290079,
"author": "David Sword",
"author_id": 132362,
"author_profile": "https://wordpress.stackexchange.com/users/132362",
"pm_score": 2,
"selected": false,
"text": "<p>This bolds the first words (or entire word, if only one) of my widget titles:</p>\n\n<pre><code>add_filter( 'widget_title', function ( $title ) {\n return preg_replace(\"/^(.+?)( |$)/\", \"<strong>$0</strong>\", $title, 1);\n}, 10, 1);\n</code></pre>\n\n<p>Breaking down the regex pattern, we have:</p>\n\n<ul>\n<li><code>^</code> is the start of the line</li>\n<li><code>(.+?)</code> is anything between our next group (in this context, a word)</li>\n<li><code>( |$)</code> means either the first space, or the end of the line\n\n<ul>\n<li>the first space would be a normal title with multiple words</li>\n<li>the end of line would mean a space wasn't found, so the title is just one word</li>\n</ul></li>\n</ul>\n\n<p>In <code>preg_replace()</code>, we have a fourth attribute set to <code>1</code>, it's the limit. This means the replace will only work on the first instance (which doesn't matter much in this context, as we know <code>$title</code> is always a single line so because of our start of line anchor <code>^</code> we know it can only work once always - but hey, why not).</p>\n\n<p>Please keep in mind I put the code in an anonymous function for minimal code (showing off). If this is for a plugin or a public theme, best to stick to doing the function call as you originally did.</p>\n"
},
{
"answer_id": 290110,
"author": "scytale",
"author_id": 128374,
"author_profile": "https://wordpress.stackexchange.com/users/128374",
"pm_score": 0,
"selected": false,
"text": "<p>Normally WP won't allow html tags <code><></code> input but will allow \"<code>[</code>\" & \"<code>]</code>\". So a simple solution is to convert say <em>\"This is [b]bold[/b]\"</em> to <em>\"This is <strong>bold</strong>\"</em>.</p>\n\n<p>In your own widget <strong>you don't even need to use</strong> <code>add_filter</code>; something like:</p>\n\n<pre><code>$title = str_replace( array(\"[b]\",\"[/b]\"), array(\"<b>\",\"</b>\"), apply_filters('widget_title', $title));\n</code></pre>\n\n<p>(then, as usual, later rendering your widget title by echoing $title) <strong>should do the trick</strong>.</p>\n\n<p>Your question refers to <code>add_filter</code>; if you need to use this function then this is simple and can easily be extended for other HTML tags:</p>\n\n<pre><code>function bold_widget_title( $title) { \n $title = str_ireplace( array('[b]','[/b]') , array('<b>','</b>'), $title); \n return $title; \n}\nadd_filter( 'widget_title', 'bold_widget_title' ); \n// the arrays can be extended for other tags e.g \"<br>\" to allow you to choose where a long title is split to a new line.\n</code></pre>\n\n<p>It is possible to allow users to enter actual HTML tags but with hindsight I don't recommend it. In one widget I allow users to enter both <code><br></code> tags and [br] but how you do this is very specific to the widget.</p>\n\n<p>Some pointers on how to do:</p>\n\n<ol>\n<li><p>tell WP to allow <code><b></code> tags in user title input e.g.</p>\n\n<pre><code>$instance['title'] = wp_kses($new_instance['title'], array('b'=>array() ), array() );\n</code></pre></li>\n<li><p>to avoid removal by filters: replace <code><b></code>s and <code></b></code>s with <code>[]</code> versions before saving</p></li>\n<li><p>make ready for rendering e.g.</p>\n\n<pre><code>$title = str_replace ( array(\"[b]\",\"[/b]\") , array(\"<b>\",\"</b>\") , apply_filters('widget_title', str_ireplace(array(\"[b]\",\"[/b]\"), array(\"<b>\",\"</b>\"),$title)));\n</code></pre></li>\n</ol>\n"
},
{
"answer_id": 290245,
"author": "scytale",
"author_id": 128374,
"author_profile": "https://wordpress.stackexchange.com/users/128374",
"pm_score": 0,
"selected": false,
"text": "<p>Having seen your comments I now assume you want to alter any widget title irrespective of user input. So new answer (I've left the old which may be of use to others).</p>\n\n<blockquote>\n <p>I am seeing the first word bold when I\n var_dump it, but the <strong> tag shows up within the actual title\n when the page renders</p>\n</blockquote>\n\n<p>Like David I find code in <em>functions.php</em> correctly adds (non escaped) bold tags when add_filter is given a priority of 10 (as in your example).</p>\n\n<p>On your site it appears that the function is adding your tags, but a later process (WP or some plugin) then escapes them converting <code><</code> to <code>&lt;</code> etc.</p>\n\n<p>Making your function run after other add_filters by \"lowering\" its priority might work e.g. <code>add_filter('widget_title', 'test', 999999, 1);</code></p>\n\n<p>If not, you could try this in your functions.php</p>\n\n<pre><code>remove_filter( 'widget_title', 'esc_html' ); // remove filter that may be added elsewhere\n\nfunction bold_first_word( $title ) { \n $title = trim(esc_html($title)); // re-apply escaping BEFORE bolding\n // or use wp_kses to remove tags except those specified (but don't allow bold tags)\n\n if (empty($title)) return $title;\n // some code to bolden first or only word (see below)\n}\nadd_filter( 'widget_title', 'bold_first_word', 10, 1);\n</code></pre>\n\n<p>Code to bold first word without resorting to regular expressions:</p>\n\n<pre><code>$first_space = strpos($title, ' ');\nif ($first_space !== false) {\n return '<strong>' . substr_replace($title, '</strong> ', $first_space, 1);\n} else {\n return '<strong>' . $title . '</strong>';\n}\n</code></pre>\n\n<p>Note: even if your function is working - it will not be called (i.e. work) with the minority of widget plugins that either do not <code>apply_filter('widget_title', ...</code> or that have some unusual title logic.</p>\n"
}
]
| 2018/01/03 | [
"https://wordpress.stackexchange.com/questions/290075",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/90300/"
]
| Is there a way to bold a specific word or part of a widget title? For example the title "Foo Bar", "Foo" here would be bold.
I tried doing the following, but the span gets outputted in the title:
```
add_filter( 'widget_title', 'test', 10, 1);
function test( $content ) {
$test = explode(' ', $content);
if ( !empty($test[1] ) ) {
$title = '<span class="this_is_bold">' . $test[0] . '</span>';
$title = $title . ' ' . $test[1];
}
return $title;
}
``` | This bolds the first words (or entire word, if only one) of my widget titles:
```
add_filter( 'widget_title', function ( $title ) {
return preg_replace("/^(.+?)( |$)/", "<strong>$0</strong>", $title, 1);
}, 10, 1);
```
Breaking down the regex pattern, we have:
* `^` is the start of the line
* `(.+?)` is anything between our next group (in this context, a word)
* `( |$)` means either the first space, or the end of the line
+ the first space would be a normal title with multiple words
+ the end of line would mean a space wasn't found, so the title is just one word
In `preg_replace()`, we have a fourth attribute set to `1`, it's the limit. This means the replace will only work on the first instance (which doesn't matter much in this context, as we know `$title` is always a single line so because of our start of line anchor `^` we know it can only work once always - but hey, why not).
Please keep in mind I put the code in an anonymous function for minimal code (showing off). If this is for a plugin or a public theme, best to stick to doing the function call as you originally did. |
290,090 | <p>I have created a custom post type called Course Documents using WordPress <a href="https://wordpress.org/plugins/custom-post-type-ui/" rel="nofollow noreferrer">Custom Post Type UI</a> plugin.
Also, I have created a new user role called Teacher.</p>
<pre><code>add_role('rpt_teacher',
'Teacher',
array(
'read' => true,
'edit_posts' => false,
'delete_posts' => false,
'publish_posts' => false,
'upload_files' => true,
)
);
</code></pre>
<p>And now I want to enable the custom post type in teacher dashboard nav menu.
I have used below code in my functions.php
but nothing happens. How can I resolve my issue?</p>
<pre><code>add_action('admin_init','rpt_add_role_caps',999);
/**
add teachers capability
*/
function rpt_add_role_caps() {
// Add the roles you'd like to administer the custom post types
$roles = array('rpt_teacher','editor','administrator');
// Loop through each role and assign capabilities
foreach($roles as $the_role) {
$role = get_role($the_role);
$role->add_cap( 'read' );
$role->add_cap( 'read_course_document');
$role->add_cap( 'edit_course_document' );
$role->add_cap( 'edit_course_documents' );
$role->add_cap( 'edit_published_course_documents' );
$role->add_cap( 'publish_course_documents' );
$role->add_cap( 'delete_published_course_documents' );
}
}
</code></pre>
| [
{
"answer_id": 290093,
"author": "Sid",
"author_id": 110516,
"author_profile": "https://wordpress.stackexchange.com/users/110516",
"pm_score": 1,
"selected": false,
"text": "<p>The way I see it, you are on the right track. You created a user and assign new capabilities to it. You just missed specifying that the new capabilities will be used to edit your custom post type.</p>\n\n<p>I have never used a plugin to create a custom post type so I am not sure how to do that using a plugin. But if you are willing to create your CPT via code you can use the following:</p>\n\n<pre><code>add_action( 'init', 'psp_register_cpt_projects');\nfunction psp_register_cpt_projects() {\n $args = array(\n 'label' => __( 'course_documents', 'course_documents' ),\n 'description' => __( 'Course document', 'course_document' ),\n 'supports' => array( 'title', 'comments', 'revisions', ),\n 'hierarchical' => false,\n 'public' => true,\n 'show_ui' => true,\n 'capability_type' => array('course_document','course_documents'),\n 'map_meta_cap' => true,\n );\n register_post_type( 'course_documents', $args );\n}\n</code></pre>\n\n<blockquote>\n <p>Note: This is just a basic code for creating a CPT. Please read <a href=\"https://codex.wordpress.org/Function_Reference/register_post_type\" rel=\"nofollow noreferrer\">this</a>\n doc in the codex to understand it thoroughly.</p>\n</blockquote>\n\n<p>Let me know if this helps you.</p>\n"
},
{
"answer_id": 290100,
"author": "Bikash Waiba",
"author_id": 121069,
"author_profile": "https://wordpress.stackexchange.com/users/121069",
"pm_score": 5,
"selected": true,
"text": "<p>I don't think the plugin adds the capabilities you are using in <code>add_cap</code> while registering the post type.</p>\n\n<p>You can modify the registered post type by adding code to themes <code>functions.php</code> file. You can do something like this.</p>\n\n<pre><code>/**\n * Overwrite args of custom post type registered by plugin\n */\nadd_filter( 'register_post_type_args', 'change_capabilities_of_course_document' , 10, 2 );\n\nfunction change_capabilities_of_course_document( $args, $post_type ){\n\n // Do not filter any other post type\n if ( 'course_document' !== $post_type ) {\n\n // Give other post_types their original arguments\n return $args;\n\n }\n\n // Change the capabilities of the \"course_document\" post_type\n $args['capabilities'] = array(\n 'edit_post' => 'edit_course_document',\n 'edit_posts' => 'edit_course_documents',\n 'edit_others_posts' => 'edit_other_course_documents',\n 'publish_posts' => 'publish_course_documents',\n 'read_post' => 'read_course_document',\n 'read_private_posts' => 'read_private_course_documents',\n 'delete_post' => 'delete_course_document'\n );\n\n // Give the course_document post type it's arguments\n return $args;\n\n}\n</code></pre>\n\n<p>Then you can do</p>\n\n<pre><code>/**\nadd teachers capability\n*/\nadd_action('admin_init','rpt_add_role_caps',999);\n\nfunction rpt_add_role_caps() {\n\n $role = get_role('teacher'); \n $role->add_cap( 'read_course_document');\n $role->add_cap( 'edit_course_document' );\n $role->add_cap( 'edit_course_documents' );\n $role->add_cap( 'edit_other_course_documents' );\n $role->add_cap( 'edit_published_course_documents' );\n $role->add_cap( 'publish_course_documents' );\n $role->add_cap( 'read_private_course_documents' );\n $role->add_cap( 'delete_course_document' );\n\n\n}\n</code></pre>\n\n<p>You don't need to add capability to administrator and editor because the <code>capability_type</code> is <code>post</code> by default while registering Custom Post Type via this plugin. You can change it, if you prefer to have custom <code>capability_type</code> based on other post type.</p>\n\n<p>Note: Make sure <code>Show in Menu</code> is set to <code>true</code>. It is <code>true</code> by default in this plugin. </p>\n"
},
{
"answer_id": 355608,
"author": "Dale Clifford",
"author_id": 96739,
"author_profile": "https://wordpress.stackexchange.com/users/96739",
"pm_score": 1,
"selected": false,
"text": "<p>I just allowed all users to show in the 'Author' selection:</p>\n\n<pre><code>add_filter( 'wp_dropdown_users_args', 'add_subscribers_to_dropdown', 10, 2 );\nfunction add_subscribers_to_dropdown( $query_args, $r ) {\n $query_args['who'] = '';\n return $query_args;\n}\n</code></pre>\n"
},
{
"answer_id": 398727,
"author": "etudor",
"author_id": 215403,
"author_profile": "https://wordpress.stackexchange.com/users/215403",
"pm_score": 1,
"selected": false,
"text": "<p>Just one thing I spent a couple of hours on worth mentioning.\nIf you have custom capabilities, and you want to update a custom role capabilities, don't do it in the add_role function.</p>\n<p>For example, this won't update the role as it already exists:</p>\n<pre><code> $role = add_role(\n 'client',\n 'Client',\n array(\n 'read' => true,\n 'edit_posts' => true,\n 'delete_posts' => false,\n CAP_READ_ADDRESS => true,\n CAP_DELETE_ADDRESS => true,\n CAP_EDIT_OTHER_ADDRESSES => true,\n CAP_READ_PRIVATE_ADDRESS => true,\n CAP_EDIT_ADDRESSES => true,\n CAP_PUBLISH_ADDRESS => true,\n CAP_EDIT_ADDRESS => true\n )\n</code></pre>\n<p>After any capabilities update, my client role won't get updated as it already exists.</p>\n<p>The safest way to add custom capabilities to a custom role is to get the role and add them after add_role</p>\n<pre><code>function addCaps() {\n $role = get_role('client');\n $role->add_cap(CAP_READ_ADDRESS, true);\n $role->add_cap(CAP_EDIT_ADDRESSES, true);\n}\n\nadd_action('admin_init', 'addCaps');\n</code></pre>\n"
}
]
| 2018/01/04 | [
"https://wordpress.stackexchange.com/questions/290090",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/66897/"
]
| I have created a custom post type called Course Documents using WordPress [Custom Post Type UI](https://wordpress.org/plugins/custom-post-type-ui/) plugin.
Also, I have created a new user role called Teacher.
```
add_role('rpt_teacher',
'Teacher',
array(
'read' => true,
'edit_posts' => false,
'delete_posts' => false,
'publish_posts' => false,
'upload_files' => true,
)
);
```
And now I want to enable the custom post type in teacher dashboard nav menu.
I have used below code in my functions.php
but nothing happens. How can I resolve my issue?
```
add_action('admin_init','rpt_add_role_caps',999);
/**
add teachers capability
*/
function rpt_add_role_caps() {
// Add the roles you'd like to administer the custom post types
$roles = array('rpt_teacher','editor','administrator');
// Loop through each role and assign capabilities
foreach($roles as $the_role) {
$role = get_role($the_role);
$role->add_cap( 'read' );
$role->add_cap( 'read_course_document');
$role->add_cap( 'edit_course_document' );
$role->add_cap( 'edit_course_documents' );
$role->add_cap( 'edit_published_course_documents' );
$role->add_cap( 'publish_course_documents' );
$role->add_cap( 'delete_published_course_documents' );
}
}
``` | I don't think the plugin adds the capabilities you are using in `add_cap` while registering the post type.
You can modify the registered post type by adding code to themes `functions.php` file. You can do something like this.
```
/**
* Overwrite args of custom post type registered by plugin
*/
add_filter( 'register_post_type_args', 'change_capabilities_of_course_document' , 10, 2 );
function change_capabilities_of_course_document( $args, $post_type ){
// Do not filter any other post type
if ( 'course_document' !== $post_type ) {
// Give other post_types their original arguments
return $args;
}
// Change the capabilities of the "course_document" post_type
$args['capabilities'] = array(
'edit_post' => 'edit_course_document',
'edit_posts' => 'edit_course_documents',
'edit_others_posts' => 'edit_other_course_documents',
'publish_posts' => 'publish_course_documents',
'read_post' => 'read_course_document',
'read_private_posts' => 'read_private_course_documents',
'delete_post' => 'delete_course_document'
);
// Give the course_document post type it's arguments
return $args;
}
```
Then you can do
```
/**
add teachers capability
*/
add_action('admin_init','rpt_add_role_caps',999);
function rpt_add_role_caps() {
$role = get_role('teacher');
$role->add_cap( 'read_course_document');
$role->add_cap( 'edit_course_document' );
$role->add_cap( 'edit_course_documents' );
$role->add_cap( 'edit_other_course_documents' );
$role->add_cap( 'edit_published_course_documents' );
$role->add_cap( 'publish_course_documents' );
$role->add_cap( 'read_private_course_documents' );
$role->add_cap( 'delete_course_document' );
}
```
You don't need to add capability to administrator and editor because the `capability_type` is `post` by default while registering Custom Post Type via this plugin. You can change it, if you prefer to have custom `capability_type` based on other post type.
Note: Make sure `Show in Menu` is set to `true`. It is `true` by default in this plugin. |
290,118 | <pre><code> wp_editor( $default_content, $editor_id,array('textarea_name' => $option_name,'media_buttons' => false,'editor_height' => 350,'teeny' => true) );
submit_button('Save', 'primary');
</code></pre>
<p>I want to create a mail template where admin can change content and put shortcode where he wants. </p>
<p>created a form and wrote the code above but when I click on save it not save the HTML formatted content.</p>
<p>please help any one</p>
| [
{
"answer_id": 290329,
"author": "result",
"author_id": 134376,
"author_profile": "https://wordpress.stackexchange.com/users/134376",
"pm_score": -1,
"selected": false,
"text": "<p>Very simple</p>\n\n<p>if (isset($_POST[$editor_id])){\n update_option('name_option_you_want', $editor_id);\n}</p>\n"
},
{
"answer_id": 293505,
"author": "Vivek Tamrakar",
"author_id": 96956,
"author_profile": "https://wordpress.stackexchange.com/users/96956",
"pm_score": 3,
"selected": true,
"text": "<pre><code>echo '<form action=\"\" class=\"booked-settings-form\" method=\"post\">';\n$default_content='<p>Mail formate</p>';\n$editor_id = 'customerCleanerMail';\n$option_name='customerCleanerMail';\n$default_content=html_entity_decode($default_content);\n$default_content=stripslashes($default_content);\nwp_editor( $default_content, $editor_id,array('textarea_name' => $option_name,'media_buttons' => false,'editor_height' => 350,'teeny' => true) );\nsubmit_button('Save', 'primary'); echo '</form>';\nif(isset($_POST['customerCleanerMail']) ){\n $var2=htmlentities(wpautop($_POST['customerCleanerMail']));\n $fff=update_option('customerCleanerMail', $var2);\n}\n</code></pre>\n\n<p>In form section i used wp_editor with his options, wp_editor\n work like html editor but when you store these data it not storing\nhtml data. so we found solution how to store html data wpautop() and\nhtmlentities() both two functions help to store html formated data</p>\n"
}
]
| 2018/01/04 | [
"https://wordpress.stackexchange.com/questions/290118",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/96956/"
]
| ```
wp_editor( $default_content, $editor_id,array('textarea_name' => $option_name,'media_buttons' => false,'editor_height' => 350,'teeny' => true) );
submit_button('Save', 'primary');
```
I want to create a mail template where admin can change content and put shortcode where he wants.
created a form and wrote the code above but when I click on save it not save the HTML formatted content.
please help any one | ```
echo '<form action="" class="booked-settings-form" method="post">';
$default_content='<p>Mail formate</p>';
$editor_id = 'customerCleanerMail';
$option_name='customerCleanerMail';
$default_content=html_entity_decode($default_content);
$default_content=stripslashes($default_content);
wp_editor( $default_content, $editor_id,array('textarea_name' => $option_name,'media_buttons' => false,'editor_height' => 350,'teeny' => true) );
submit_button('Save', 'primary'); echo '</form>';
if(isset($_POST['customerCleanerMail']) ){
$var2=htmlentities(wpautop($_POST['customerCleanerMail']));
$fff=update_option('customerCleanerMail', $var2);
}
```
In form section i used wp\_editor with his options, wp\_editor
work like html editor but when you store these data it not storing
html data. so we found solution how to store html data wpautop() and
htmlentities() both two functions help to store html formated data |
290,120 | <p>I have two custom fields, and both have numeric values:</p>
<p>tnid_01</p>
<p>tnid_01old</p>
<p>Custom Field 'tnid_01' exists for all posts.</p>
<p>Custom Field 'tnid_01old' only exists for some posts.</p>
<p>I am trying to replace the value of 'tnid_01' with the value of 'tnid_01old', but only if 'tnid_01old' exists.</p>
<p>This is what i have so far, but i get a mysql error:</p>
<pre><code>Update wp_postmeta (post_id, meta_key, meta_value)(
SELECT post_id, 'tnid_01', meta_value
FROM wp_postmeta
WHERE meta_key='tnid_01old'
);
</code></pre>
<p>thx</p>
| [
{
"answer_id": 290329,
"author": "result",
"author_id": 134376,
"author_profile": "https://wordpress.stackexchange.com/users/134376",
"pm_score": -1,
"selected": false,
"text": "<p>Very simple</p>\n\n<p>if (isset($_POST[$editor_id])){\n update_option('name_option_you_want', $editor_id);\n}</p>\n"
},
{
"answer_id": 293505,
"author": "Vivek Tamrakar",
"author_id": 96956,
"author_profile": "https://wordpress.stackexchange.com/users/96956",
"pm_score": 3,
"selected": true,
"text": "<pre><code>echo '<form action=\"\" class=\"booked-settings-form\" method=\"post\">';\n$default_content='<p>Mail formate</p>';\n$editor_id = 'customerCleanerMail';\n$option_name='customerCleanerMail';\n$default_content=html_entity_decode($default_content);\n$default_content=stripslashes($default_content);\nwp_editor( $default_content, $editor_id,array('textarea_name' => $option_name,'media_buttons' => false,'editor_height' => 350,'teeny' => true) );\nsubmit_button('Save', 'primary'); echo '</form>';\nif(isset($_POST['customerCleanerMail']) ){\n $var2=htmlentities(wpautop($_POST['customerCleanerMail']));\n $fff=update_option('customerCleanerMail', $var2);\n}\n</code></pre>\n\n<p>In form section i used wp_editor with his options, wp_editor\n work like html editor but when you store these data it not storing\nhtml data. so we found solution how to store html data wpautop() and\nhtmlentities() both two functions help to store html formated data</p>\n"
}
]
| 2018/01/04 | [
"https://wordpress.stackexchange.com/questions/290120",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/110297/"
]
| I have two custom fields, and both have numeric values:
tnid\_01
tnid\_01old
Custom Field 'tnid\_01' exists for all posts.
Custom Field 'tnid\_01old' only exists for some posts.
I am trying to replace the value of 'tnid\_01' with the value of 'tnid\_01old', but only if 'tnid\_01old' exists.
This is what i have so far, but i get a mysql error:
```
Update wp_postmeta (post_id, meta_key, meta_value)(
SELECT post_id, 'tnid_01', meta_value
FROM wp_postmeta
WHERE meta_key='tnid_01old'
);
```
thx | ```
echo '<form action="" class="booked-settings-form" method="post">';
$default_content='<p>Mail formate</p>';
$editor_id = 'customerCleanerMail';
$option_name='customerCleanerMail';
$default_content=html_entity_decode($default_content);
$default_content=stripslashes($default_content);
wp_editor( $default_content, $editor_id,array('textarea_name' => $option_name,'media_buttons' => false,'editor_height' => 350,'teeny' => true) );
submit_button('Save', 'primary'); echo '</form>';
if(isset($_POST['customerCleanerMail']) ){
$var2=htmlentities(wpautop($_POST['customerCleanerMail']));
$fff=update_option('customerCleanerMail', $var2);
}
```
In form section i used wp\_editor with his options, wp\_editor
work like html editor but when you store these data it not storing
html data. so we found solution how to store html data wpautop() and
htmlentities() both two functions help to store html formated data |
290,128 | <p>The code in question β</p>
<pre><code><?php if ( has_post_thumbnail() ) {the_post_thumbnail();} ?>
</code></pre>
<p>The generated output in <strong>browser</strong> is like this β </p>
<pre><code><img width="1620" height="973" src="..../site04/wp-content/uploads/2018/01/audi_ileana.jpg" class="attachment-post-thumbnail size-post-thumbnail wp-post-image" alt="" srcset="..../site04/wp-content/uploads/2018/01/audi_ileana.jpg 1620w, http://......./site04/wp-content/uploads/2018/01/audi_ileana-300x180.jpg 300w, ....../site04/wp-content/uploads/2018/01/audi_ileana-768x461.jpg 768w, http://....../site04/wp-content/uploads/2018/01/audi_ileana-1024x615.jpg 1024w" sizes="(max-width: 1620px) 100vw, 1620px">
</code></pre>
<h1>Anticipated result β</h1>
<p>I want that height should output as "auto" value. </p>
<hr>
<p><strong>I tried this:</strong></p>
<pre><code><div class="pimg">
<?php if ( has_post_thumbnail() ) {the_post_thumbnail();} ?>
</div>
</code></pre>
<p>and its css:</p>
<pre><code>.pimg img {max-with:100%; height:auto;}
</code></pre>
| [
{
"answer_id": 290131,
"author": "Andrew",
"author_id": 50767,
"author_profile": "https://wordpress.stackexchange.com/users/50767",
"pm_score": 3,
"selected": true,
"text": "<p>You can use a filter to remove height and width attributes from images, as explained in this <a href=\"https://css-tricks.com/snippets/wordpress/remove-width-and-height-attributes-from-inserted-images/\" rel=\"nofollow noreferrer\">CSS Tricks</a>. Place the following in your themes <code>functions.php</code> file.</p>\n\n<pre><code>add_filter( 'post_thumbnail_html', 'remove_width_attribute', 10 );\nadd_filter( 'image_send_to_editor', 'remove_width_attribute', 10 );\n\nfunction remove_width_attribute( $html ) {\n $html = preg_replace( '/(width|height)=\"\\d*\"\\s/', \"\", $html );\n return $html;\n}\n</code></pre>\n"
},
{
"answer_id": 290142,
"author": "D. Dan",
"author_id": 133528,
"author_profile": "https://wordpress.stackexchange.com/users/133528",
"pm_score": 1,
"selected": false,
"text": "<p>Alternatively you could try using <a href=\"https://developer.wordpress.org/reference/functions/get_the_post_thumbnail_url/\" rel=\"nofollow noreferrer\">another</a> function to get just the url then echo that inside img:</p>\n\n<pre><code><img src=\"<?php echo get_the_post_thumbnail_url(); ?>\" alt=\"Post thumbnail image\">\n</code></pre>\n\n<p>And style it completely yourself.</p>\n"
}
]
| 2018/01/04 | [
"https://wordpress.stackexchange.com/questions/290128",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/105791/"
]
| The code in question β
```
<?php if ( has_post_thumbnail() ) {the_post_thumbnail();} ?>
```
The generated output in **browser** is like this β
```
<img width="1620" height="973" src="..../site04/wp-content/uploads/2018/01/audi_ileana.jpg" class="attachment-post-thumbnail size-post-thumbnail wp-post-image" alt="" srcset="..../site04/wp-content/uploads/2018/01/audi_ileana.jpg 1620w, http://......./site04/wp-content/uploads/2018/01/audi_ileana-300x180.jpg 300w, ....../site04/wp-content/uploads/2018/01/audi_ileana-768x461.jpg 768w, http://....../site04/wp-content/uploads/2018/01/audi_ileana-1024x615.jpg 1024w" sizes="(max-width: 1620px) 100vw, 1620px">
```
Anticipated result β
====================
I want that height should output as "auto" value.
---
**I tried this:**
```
<div class="pimg">
<?php if ( has_post_thumbnail() ) {the_post_thumbnail();} ?>
</div>
```
and its css:
```
.pimg img {max-with:100%; height:auto;}
``` | You can use a filter to remove height and width attributes from images, as explained in this [CSS Tricks](https://css-tricks.com/snippets/wordpress/remove-width-and-height-attributes-from-inserted-images/). Place the following in your themes `functions.php` file.
```
add_filter( 'post_thumbnail_html', 'remove_width_attribute', 10 );
add_filter( 'image_send_to_editor', 'remove_width_attribute', 10 );
function remove_width_attribute( $html ) {
$html = preg_replace( '/(width|height)="\d*"\s/', "", $html );
return $html;
}
``` |
290,139 | <p>I am using a hook from Paid Membership pro to add ACF fields on a registration form.</p>
<pre><code>function insert_acf() {
echo "<p><div id='content-creator'>Test</div></p>
<p><?php the_field('organisation_name'); ?></p>";
};
add_action('pmpro_checkout_before_submit_button','insert_acf');
</code></pre>
<p>Problem 1: The test div works but it is not displaying the ACF field</p>
<p>Problem 2: How do I associate this ACF field to the newly created subscriber</p>
<p>TIA</p>
| [
{
"answer_id": 290131,
"author": "Andrew",
"author_id": 50767,
"author_profile": "https://wordpress.stackexchange.com/users/50767",
"pm_score": 3,
"selected": true,
"text": "<p>You can use a filter to remove height and width attributes from images, as explained in this <a href=\"https://css-tricks.com/snippets/wordpress/remove-width-and-height-attributes-from-inserted-images/\" rel=\"nofollow noreferrer\">CSS Tricks</a>. Place the following in your themes <code>functions.php</code> file.</p>\n\n<pre><code>add_filter( 'post_thumbnail_html', 'remove_width_attribute', 10 );\nadd_filter( 'image_send_to_editor', 'remove_width_attribute', 10 );\n\nfunction remove_width_attribute( $html ) {\n $html = preg_replace( '/(width|height)=\"\\d*\"\\s/', \"\", $html );\n return $html;\n}\n</code></pre>\n"
},
{
"answer_id": 290142,
"author": "D. Dan",
"author_id": 133528,
"author_profile": "https://wordpress.stackexchange.com/users/133528",
"pm_score": 1,
"selected": false,
"text": "<p>Alternatively you could try using <a href=\"https://developer.wordpress.org/reference/functions/get_the_post_thumbnail_url/\" rel=\"nofollow noreferrer\">another</a> function to get just the url then echo that inside img:</p>\n\n<pre><code><img src=\"<?php echo get_the_post_thumbnail_url(); ?>\" alt=\"Post thumbnail image\">\n</code></pre>\n\n<p>And style it completely yourself.</p>\n"
}
]
| 2018/01/04 | [
"https://wordpress.stackexchange.com/questions/290139",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/133457/"
]
| I am using a hook from Paid Membership pro to add ACF fields on a registration form.
```
function insert_acf() {
echo "<p><div id='content-creator'>Test</div></p>
<p><?php the_field('organisation_name'); ?></p>";
};
add_action('pmpro_checkout_before_submit_button','insert_acf');
```
Problem 1: The test div works but it is not displaying the ACF field
Problem 2: How do I associate this ACF field to the newly created subscriber
TIA | You can use a filter to remove height and width attributes from images, as explained in this [CSS Tricks](https://css-tricks.com/snippets/wordpress/remove-width-and-height-attributes-from-inserted-images/). Place the following in your themes `functions.php` file.
```
add_filter( 'post_thumbnail_html', 'remove_width_attribute', 10 );
add_filter( 'image_send_to_editor', 'remove_width_attribute', 10 );
function remove_width_attribute( $html ) {
$html = preg_replace( '/(width|height)="\d*"\s/', "", $html );
return $html;
}
``` |
290,143 | <p>I wanted to add a new image size to the theme I have. But the image sizes are not working correctly.</p>
<p>My code:</p>
<pre><code>add_theme_support( 'post-thumbnails' );
add_image_size( 'bch-microsite-slider-image', 1450, 620 );
add_image_size( 'bch-microsite-hero-image', 1450, 315 );
add_image_size( 'bch-microsite-blog-image', 1000, 670, array( 'center', 'center') );
add_image_size( 'bch-microsite-blog-image1', 1000, 670 );
add_image_size( 'bch-microsite-blog-image2', 1000, 650 );
add_image_size( 'bch-microsite-blog-image3', 1000, 620 );
</code></pre>
<p>The first two calls were already in the theme, but the apparently never worked right but I never really noticed since I wasn't using them. I added the 3rd call as what I wanted, and the 4th through 6th calls are an experiment. </p>
<p>I used the plugin "Display All Image Sizes" to make sure I wasn't looking at things wrong, but in the Media Library, a newly uploaded image shows the following image sizes:
<a href="https://i.stack.imgur.com/xqBoi.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/xqBoi.png" alt="enter image description here"></a></p>
<p>The new sizes never exceed the "large" size, but I don't see a reference to that anywhere in the documentation. Do I have to change the "large" size, or is there some other problem? Any help would be greatly appreciated.</p>
<p>Here are the results of running Regenerate Thumbnails are a single image:
<a href="https://i.stack.imgur.com/sQtBV.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/sQtBV.png" alt="enter image description here"></a>
All the image sizes reported by Regenerate Thumbnails are correct and it generates the correctly sized image files in the uploads folder. However, when selecting the image from the media library, the incorrect sizes are still being shown:
<a href="https://i.stack.imgur.com/gAmVf.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/gAmVf.png" alt="enter image description here"></a></p>
<p>When the 3rd size is inserted into a post the code uses the correctly sized file (artwork-1-1000x670.jpg) but uses the size reflected in the image size drop-down list (640 by 429).</p>
| [
{
"answer_id": 290131,
"author": "Andrew",
"author_id": 50767,
"author_profile": "https://wordpress.stackexchange.com/users/50767",
"pm_score": 3,
"selected": true,
"text": "<p>You can use a filter to remove height and width attributes from images, as explained in this <a href=\"https://css-tricks.com/snippets/wordpress/remove-width-and-height-attributes-from-inserted-images/\" rel=\"nofollow noreferrer\">CSS Tricks</a>. Place the following in your themes <code>functions.php</code> file.</p>\n\n<pre><code>add_filter( 'post_thumbnail_html', 'remove_width_attribute', 10 );\nadd_filter( 'image_send_to_editor', 'remove_width_attribute', 10 );\n\nfunction remove_width_attribute( $html ) {\n $html = preg_replace( '/(width|height)=\"\\d*\"\\s/', \"\", $html );\n return $html;\n}\n</code></pre>\n"
},
{
"answer_id": 290142,
"author": "D. Dan",
"author_id": 133528,
"author_profile": "https://wordpress.stackexchange.com/users/133528",
"pm_score": 1,
"selected": false,
"text": "<p>Alternatively you could try using <a href=\"https://developer.wordpress.org/reference/functions/get_the_post_thumbnail_url/\" rel=\"nofollow noreferrer\">another</a> function to get just the url then echo that inside img:</p>\n\n<pre><code><img src=\"<?php echo get_the_post_thumbnail_url(); ?>\" alt=\"Post thumbnail image\">\n</code></pre>\n\n<p>And style it completely yourself.</p>\n"
}
]
| 2018/01/04 | [
"https://wordpress.stackexchange.com/questions/290143",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/78341/"
]
| I wanted to add a new image size to the theme I have. But the image sizes are not working correctly.
My code:
```
add_theme_support( 'post-thumbnails' );
add_image_size( 'bch-microsite-slider-image', 1450, 620 );
add_image_size( 'bch-microsite-hero-image', 1450, 315 );
add_image_size( 'bch-microsite-blog-image', 1000, 670, array( 'center', 'center') );
add_image_size( 'bch-microsite-blog-image1', 1000, 670 );
add_image_size( 'bch-microsite-blog-image2', 1000, 650 );
add_image_size( 'bch-microsite-blog-image3', 1000, 620 );
```
The first two calls were already in the theme, but the apparently never worked right but I never really noticed since I wasn't using them. I added the 3rd call as what I wanted, and the 4th through 6th calls are an experiment.
I used the plugin "Display All Image Sizes" to make sure I wasn't looking at things wrong, but in the Media Library, a newly uploaded image shows the following image sizes:
[](https://i.stack.imgur.com/xqBoi.png)
The new sizes never exceed the "large" size, but I don't see a reference to that anywhere in the documentation. Do I have to change the "large" size, or is there some other problem? Any help would be greatly appreciated.
Here are the results of running Regenerate Thumbnails are a single image:
[](https://i.stack.imgur.com/sQtBV.png)
All the image sizes reported by Regenerate Thumbnails are correct and it generates the correctly sized image files in the uploads folder. However, when selecting the image from the media library, the incorrect sizes are still being shown:
[](https://i.stack.imgur.com/gAmVf.png)
When the 3rd size is inserted into a post the code uses the correctly sized file (artwork-1-1000x670.jpg) but uses the size reflected in the image size drop-down list (640 by 429). | You can use a filter to remove height and width attributes from images, as explained in this [CSS Tricks](https://css-tricks.com/snippets/wordpress/remove-width-and-height-attributes-from-inserted-images/). Place the following in your themes `functions.php` file.
```
add_filter( 'post_thumbnail_html', 'remove_width_attribute', 10 );
add_filter( 'image_send_to_editor', 'remove_width_attribute', 10 );
function remove_width_attribute( $html ) {
$html = preg_replace( '/(width|height)="\d*"\s/', "", $html );
return $html;
}
``` |
290,147 | <p>I'm making a skin for The Grid plugin (<a href="https://theme-one.com/docs/the-grid/#developer_guide" rel="nofollow noreferrer">https://theme-one.com/docs/the-grid/#developer_guide</a>).</p>
<p>All the products are virtual and downloadable β I've managed to make an add to cart function, but need to download products instantly too. Is there a meta key for the file url (combed the database and couldn't spot one) or a way to get it?</p>
<p>Currently I've got something that just returns an array:</p>
<pre><code>$output .= '<p><a href="' . $tg_el->get_item_meta('_downloadable_files') . '" download target="_blank"><i class="fa fa-download"></i> Download Image</a></p>';
</code></pre>
<p>Thought I'd found a possible solution: <a href="https://wordpress.stackexchange.com/a/199884/134263">https://wordpress.stackexchange.com/a/199884/134263</a> but am not great with php and I'm unsure how to implement it.</p>
<p>Any pointers would be much appreciated!</p>
| [
{
"answer_id": 291312,
"author": "Dannie Herdyawan",
"author_id": 68053,
"author_profile": "https://wordpress.stackexchange.com/users/68053",
"pm_score": 0,
"selected": false,
"text": "<pre><code><?php \n $downloads = $product->get_files();\n foreach( $downloads as $key => $each_download ) {\n echo '<p><a href=\"'.$each_download[\"file\"].'\" download><i class=\"fa fa-download\"></i> Download Image</a></p>';\n }\n?>\n</code></pre>\n"
},
{
"answer_id": 355443,
"author": "Amit Joshi",
"author_id": 174350,
"author_profile": "https://wordpress.stackexchange.com/users/174350",
"pm_score": 0,
"selected": false,
"text": "<p>as i used @dannie Herdyawans code snippet, it shows that <code>get_files()</code> function is deprecated.<br>\nso instead of that use <code>get_downloads()</code> function. listed below example. </p>\n\n<pre><code>$downloads = $productObj->get_downloads();\nif ($downloads):\n foreach ($downloads as $key => $each_download) {\n $product->productDownloadUrl = $each_download['file'];\n $product->productDownloadName = $each_download['name'];\n }\nendif;\n</code></pre>\n"
},
{
"answer_id": 382154,
"author": "Santanu",
"author_id": 183304,
"author_profile": "https://wordpress.stackexchange.com/users/183304",
"pm_score": 2,
"selected": false,
"text": "<pre><code><?php $downloads = $product->get_files();\n foreach( $downloads as $key => $download ) {\n echo '<p class="download-link"><a href="' . esc_url( $download['file'] ) . '">' . $download['name'] . '</a></p>';\n } ?>\n</code></pre>\n<p>Check this.. Worked for me.</p>\n"
}
]
| 2018/01/04 | [
"https://wordpress.stackexchange.com/questions/290147",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/134263/"
]
| I'm making a skin for The Grid plugin (<https://theme-one.com/docs/the-grid/#developer_guide>).
All the products are virtual and downloadable β I've managed to make an add to cart function, but need to download products instantly too. Is there a meta key for the file url (combed the database and couldn't spot one) or a way to get it?
Currently I've got something that just returns an array:
```
$output .= '<p><a href="' . $tg_el->get_item_meta('_downloadable_files') . '" download target="_blank"><i class="fa fa-download"></i> Download Image</a></p>';
```
Thought I'd found a possible solution: <https://wordpress.stackexchange.com/a/199884/134263> but am not great with php and I'm unsure how to implement it.
Any pointers would be much appreciated! | ```
<?php $downloads = $product->get_files();
foreach( $downloads as $key => $download ) {
echo '<p class="download-link"><a href="' . esc_url( $download['file'] ) . '">' . $download['name'] . '</a></p>';
} ?>
```
Check this.. Worked for me. |
290,175 | <p>My theme has an option on its page builder called "show portfolio category filter buttons" which places filter buttons for portfolio categories. As you can see from the following link, it fetches my portfolio categories, but when i push the buttons its not doing anyting. It was working before but it suddenly stopped working. Why do you think it's not working?</p>
<p><a href="http://www.ekn.sinankarabulut.com/tum-urunler/dikey-enjeksiyonlar/" rel="nofollow noreferrer">http://www.ekn.sinankarabulut.com/tum-urunler/dikey-enjeksiyonlar/</a></p>
<p>Thanks...</p>
| [
{
"answer_id": 290186,
"author": "Cedon",
"author_id": 80069,
"author_profile": "https://wordpress.stackexchange.com/users/80069",
"pm_score": 1,
"selected": false,
"text": "<p>Looks like there maybe a problem with your <code>plugins.js</code> on line 35 according to my console. I'm getting the error <code>TypeError: portfolioContainer.imagesLoaded is not a function.</code></p>\n\n<p>The code in question is:</p>\n\n<pre><code>if (jQuery().isotope){\n var portfolioContainer = jQuery('.w-portfolio.type_sortable .w-portfolio-list-h');\n if (portfolioContainer) {\n portfolioContainer.imagesLoaded(function(){\n portfolioContainer.isotope({\n itemSelector : '.w-portfolio-item',\n layoutMode : 'fitRows'\n });\n });\n\n jQuery('.w-filters-item').each(function() {\n var item = jQuery(this),\n link = item.find('.w-filters-item-link');\n link.click(function(){\n if ( ! item.hasClass('active')) {\n jQuery('.w-filters-item').removeClass('active');\n item.addClass('active');\n var selector = jQuery(this).attr('data-filter');\n portfolioContainer.isotope({ filter: selector });\n return false;\n }\n\n });\n });\n jQuery('.w-portfolio-item-meta-tags a').each(function() {\n\n jQuery(this).click(function(){\n var selector = jQuery(this).attr('data-filter'),\n topFilterLink = jQuery('a[class=\"w-filters-item-link\"][data-filter=\"'+selector+'\"]'),\n topFilter = topFilterLink.parent('.w-filters-item');\n if ( ! topFilter.hasClass('active')) {\n jQuery('.w-filters-item').removeClass('active');\n topFilter.addClass('active');\n portfolioContainer.isotope({ filter: selector });\n return false;\n }\n\n });\n });\n\n }\n</code></pre>\n\n<p>So it looks like it's an issue with the <a href=\"https://isotope.metafizzy.co/\" rel=\"nofollow noreferrer\">Isotope.js</a> library and how your theme is implementing it. I tried to look at the theme itself in a demo but it is apparently no longer available.</p>\n\n<p>Since it is a premium theme, you might want to check with the place you got it from and look into support.</p>\n"
},
{
"answer_id": 290194,
"author": "Gary D",
"author_id": 51921,
"author_profile": "https://wordpress.stackexchange.com/users/51921",
"pm_score": 0,
"selected": false,
"text": "<p>imagesLoaded is a js library made by the same author as isotope.js -\na script that is included in your footer. My guess is <a href=\"https://imagesloaded.desandro.com/\" rel=\"nofollow noreferrer\">imagesLoaded</a> is not being enqueued properly, or should have been included in your build of isotope.js.</p>\n"
}
]
| 2018/01/04 | [
"https://wordpress.stackexchange.com/questions/290175",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/130811/"
]
| My theme has an option on its page builder called "show portfolio category filter buttons" which places filter buttons for portfolio categories. As you can see from the following link, it fetches my portfolio categories, but when i push the buttons its not doing anyting. It was working before but it suddenly stopped working. Why do you think it's not working?
<http://www.ekn.sinankarabulut.com/tum-urunler/dikey-enjeksiyonlar/>
Thanks... | Looks like there maybe a problem with your `plugins.js` on line 35 according to my console. I'm getting the error `TypeError: portfolioContainer.imagesLoaded is not a function.`
The code in question is:
```
if (jQuery().isotope){
var portfolioContainer = jQuery('.w-portfolio.type_sortable .w-portfolio-list-h');
if (portfolioContainer) {
portfolioContainer.imagesLoaded(function(){
portfolioContainer.isotope({
itemSelector : '.w-portfolio-item',
layoutMode : 'fitRows'
});
});
jQuery('.w-filters-item').each(function() {
var item = jQuery(this),
link = item.find('.w-filters-item-link');
link.click(function(){
if ( ! item.hasClass('active')) {
jQuery('.w-filters-item').removeClass('active');
item.addClass('active');
var selector = jQuery(this).attr('data-filter');
portfolioContainer.isotope({ filter: selector });
return false;
}
});
});
jQuery('.w-portfolio-item-meta-tags a').each(function() {
jQuery(this).click(function(){
var selector = jQuery(this).attr('data-filter'),
topFilterLink = jQuery('a[class="w-filters-item-link"][data-filter="'+selector+'"]'),
topFilter = topFilterLink.parent('.w-filters-item');
if ( ! topFilter.hasClass('active')) {
jQuery('.w-filters-item').removeClass('active');
topFilter.addClass('active');
portfolioContainer.isotope({ filter: selector });
return false;
}
});
});
}
```
So it looks like it's an issue with the [Isotope.js](https://isotope.metafizzy.co/) library and how your theme is implementing it. I tried to look at the theme itself in a demo but it is apparently no longer available.
Since it is a premium theme, you might want to check with the place you got it from and look into support. |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.