Ask your WordPress questions! Pay money and get answers fast! Comodo Trusted Site Seal
Official PayPal Seal

Using values from an array WordPress

  • SOLVED

I found this function (https://www.axfon.com/how-to-get-primary-category-on-wordpress-using-yoast-plugin/) to get the primary category (a feature of Yoast SEO plugin)

I added that to my functions.php

And then as that page suggested I added to my template file:
<?php echo '<pre>'.print_r(get_primary_category(), true).'</pre>'; ?>

This outputs an array with the correct information in my loop.
Array
(
[url] => http://mysite.com/category/english-football/championship-betting-tips/
[slug] => championship-betting-tips
[title] => Championship
[id] => 19
)


How do I put this information into a usable bit of code like this?
<a href="<?php echo $url; ?>"><?php echo $title; ?></a>

Answers (7)

2019-10-04

Shabeer M answers:

In the template file, add the code like this
<?php $categ= get_primary_category(); ?>
<a href="<?php echo $categ['url'] ?>"><?php echo $categ['title']; ?></a>

Or you cN write like
<?php extract(get_primary_category()); ?>
<a href="<?php echo $url; ?>"><?php echo $title; ?></a>

Please reply me if you need any more assistance or the reply is not what you expect.

2019-10-04

Navjot Singh answers:

Use something like

<?php $pcat = get_primary_category(); ?>
<a href="<?php echo $pcat['url']; ?>"><?php echo $pcat['title']; ?></a>

2019-10-04

John Cotton answers:

<?php
$cat = get_primary_category();
printf( '<a href="%s">%s</a>', $cat['url'], $cat['title'] );
?>

2019-10-04

Mohammed Remeez answers:

Hello brother,
Just try this ,

$primaryCategoryInfo = get_primary_category();
$url = $primaryCategoryInfo['url'];
$title = $primaryCategoryInfo['title'];

Now you have the category info in variables $url and $title.
<a href="<?php echo $url; ?>"><?php echo $title ?></a>
Happy coding,
Thanks

2019-10-04

Hugo Gonçalves answers:

Hi Ross!

In what way, do you want to make use of this in the loop?
Have you tried something like?

echo get_primary_category()["url"];


Cheers
Hugo

2019-10-04

timDesain Nanang answers:

try this one:
<?php extract( get_primary_category() ); ?>
<a href="<?php echo $url; ?>"><?php echo $title; ?></a>

2019-10-04

Darlene Grace Arcenal answers:

$cat = get_primary_category(get_the_ID(), true)
<a href="<?php echo $cat['url']; ?>"><?php echo $cat['title']; ?></a>